Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c语言中的遍历子串_C_String_Pointers_Substring - Fatal编程技术网

c语言中的遍历子串

c语言中的遍历子串,c,string,pointers,substring,C,String,Pointers,Substring,我正在尝试编写一个方法:traverseKeyAndValue(文本),它将遍历多个键值对的字符串并打印。i、 e,如果传递了“key1:value1,key2:value2,key3:value3”,它将提取键和值。 我使用了另一种方法,它基于起始文本和结束文本生成子字符串。 以下是我的代码: void extractSubstring (char *source, char *dest, char *startingText, char *endingText, bool includeSt

我正在尝试编写一个方法:traverseKeyAndValue(文本),它将遍历多个键值对的字符串并打印。i、 e,如果传递了“key1:value1,key2:value2,key3:value3”,它将提取键和值。 我使用了另一种方法,它基于起始文本和结束文本生成子字符串。 以下是我的代码:

void extractSubstring (char *source, char *dest, char *startingText, char *endingText, bool includeStart) {
     size_t sourceLen = strlen(source);
     size_t startLen = strlen(startingText); 
     size_t endingIndex = sourceLen; 
     source = strstr (source, startingText); 
     if(!includeStart){ 
        source+=startLen; 
        } 
     if(strlen(endingText)>0){ 
        endingIndex = strstr (source, endingText) - source; 
         strncpy(dest, source, endingIndex); 
     } 
     else { 
        strcpy (dest, source); 
     } 
     dest[endingIndex] = '\0';
}

void traverseKeyAndValue(char *inputText){
    int i=0;
    while(inputText[i]!='\0'){
        char key[18];
        char value[8];
        extractSubstring(inputText,key,"",":",false);
        printf(key);
        extractSubstring(inputText,value,":",",",false);
        printf(value);
        size_t keylen = strlen(key);
        size_t valuelen= strlen(value);
        int total= keylen+valuelen+1;
        inputText+=total;
    }
}

我已经使用了一个指针inputText,我在每次迭代中都会按key+值的长度递增它,以指向下一个条目。但这是“无输出”

我展示了一个如何使用
strtok
的简单示例。我假设输入来自
fgets
(保留任何换行符)

#包括
#包括
内部主(空)
{
字符输入[]=“key1:value1,key2:value2,key3:value3\n”;//来自fgets的示例输入
字符分隔符[]=“,:\t\n”;//分隔符
char*tok;
tok=strtok(输入,单独);
while(tok){
printf(“%-20s”,tok);
tok=strtok(空,单独);
如果(tok){
printf(“%s”,tok);
tok=strtok(空,单独);
}
printf(“\n”);
}
}
程序输出:

key1 value1 key2 value2 key3 value3 键1值1 键2值2 键3值3 有比
strtok
更好的功能,它不是可重入的,例如
strtok\u r
strtok\u s
strep
,具体取决于平台


可以对该示例进行改进,以处理缺少的值字段,但这是一个基本演示。

“这不起作用”不是错误描述,请阅读。另外,请提供一个答案,如果没有它,您的问题是离题的。您对
strtok
和其他(更好的)相关函数有什么反对意见?您应该在
gdb
中运行,并执行
bt
它告诉您问题出在哪里<代码>gdb告诉这行
strncpy(dest,source,endingIndex)做一些乱七八糟的事情。
key1                value1
key2                value2
key3                value3