【发布时间】:2014-12-03 17:31:17
【问题描述】:
如何分割一个未知分隔符的字符串?
我需要像
这样拆分一个字符串'3.584731 60.739211,3.590472 60.738030,3.592740: 60.736220', * *)
在**之间我要输入一个分隔符,谁会用分隔符来分割这个字符串。
举例
If *:*
3.584731 60.739211,3.590472 60.738030,3.592740
60.736220
我知道 strtok() 拆分字符串。但是我必须如何使用它,代码不知道分隔符并且用户必须插入它。这是我的代码。
PG_FUNCTION_INFO_V1(benchmark);
Datum
benchmark(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
int call_cntr;
int max_calls;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
//As Counters
int i = 0, j = 0;
//To get the every SingleString from the Table
char *k = text_to_cstring(PG_GETARG_TEXT_P(0));
//The Delimiter
char *c (0);
//the temporary "memory"
char * temp = NULL;
//The final result
//Need as an Array
//From ["x1 y1,x2 y2,...xn yn"] Split on the ','
//to ["x1 y1","x2 y2",..."xn yn"] Split on the ' '
//to the final ["x1","y1","x2","y2"..."xn","yn"]
char**result[a] = {0};
if (SRF_IS_FIRSTCALL())
{
{
MemoryContext oldcontext;
//create a function context for cross-call persistence
funcctx = SRF_FIRSTCALL_INIT();
//reqdim = (PG_NARGS() MAXDIM)
// SRF_RETURN_DONE(funcctx);
// switch to memory context appropriate for multiple function calls
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* total number of tuples to be returned */
funcctx->max_calls = PG_GETARG_UINT32(0);
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
//Still dont know what attinmeta is
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
MemoryContextSwitchTo(oldcontext);
}
call_cntr = funcctx->call_cntr;
max_calls = funcctx->max_calls;
attinmeta = funcctx->attinmeta;
result[a] = funcctx->result[a];
temp = funcctx->temp;
*k = funcctx->*k;
delim = funcctx->delim;
c = funcctx->c;
//here is the difficult part
if(*k)
{
temp = strtok(k,delim) //the delimiter
while (temp)
{
//palloc or malloc whats the difference ?
result[a] = palloc...
strcpy(result[a],temp)
temp = strtok (NULL,delim)
i++;
}
for (j = 0; j < i; j++)
printf("[%d] sub-string is %s\n", (j+1), result[j]);
for (j = 0; j < i; j++)
SRF_RETURN_NEXT(funcctx,result[a]);
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
这是对的吗? palloc 还是 malloc ?在这种情况下有什么区别以及如何使用它? 我试着做很多笔记,因为我希望你能理解这一点:) 不要太难我刚开始使用程序:)
【问题讨论】:
-
我不知道
unnest(),但您想要的是strtok()或strtok_r()。 -
您查看我在之前评论中提供的链接了吗?如果您告诉我们您不明白的部分,我们可以解释。
-
再次用代码重新编辑,但不知道他是否正确
-
不不,你弄错了。让我为你写一个示例代码。给我一些时间。
-
为什么标记为
plpgsql?我没有看到联系。可能重复:stackoverflow.com/questions/27148516/…
标签: c postgresql