Sha*_*ars 7 c string c-strings
我尝试使用strncmp,但它只有在我给它一个特定数量的字节我想要提取时才有效.
char line[256] = This "is" an example. //I want to extract "is"
char line[256] = This is "also" an example. // I want to extract "also"
char line[256] = This is the final "example". // I want to extract "example"
char substring[256]
Run Code Online (Sandbox Code Playgroud)
我如何提取""之间的所有元素?并把它放在变量substring?
注意:在我意识到编写代码会导致问题strtok而不喜欢操作const char*变量之后,我编辑了这个答案.这更像是我编写示例的工件,而不是基本原理的问题 - 但显然它应该是双重downvote.所以我修好了.
以下工作(使用gcc在Mac OS 10.7上测试):
#include <stdio.h>
#include <string.h>
int main(void) {
const char* lineConst = "This \"is\" an example"; // the "input string"
char line[256]; // where we will put a copy of the input
char *subString; // the "result"
strcpy(line, lineConst);
subString = strtok(line,"\""); // find the first double quote
subString=strtok(NULL,"\""); // find the second double quote
printf("the thing in between quotes is '%s'\n", subString);
}
Run Code Online (Sandbox Code Playgroud)
以下是它的工作原理:strtok查找"分隔符"(第二个参数) - 在本例中为第一个参数".在内部,它知道"它到底有多远",如果你用NULL第一个参数(而不是a char*)再次调用它,它将从那里再次开始.因此,在第二次调用时,它返回"恰好是第一个和第二个双引号之间的字符串".这是你想要的.
警告: strtok通常会'\0'在"吃掉"输入时替换分隔符.因此,您必须依靠此方法修改输入字符串.如果这是不可接受的,您必须先制作本地副本.本质上,当我将字符串常量复制到变量时,我在上面这样做.通过调用line=malloc(strlen(lineConst)+1);和free(line);之后执行此操作会更简洁 - 但是如果您打算将其包装在函数内部,则必须考虑返回值在函数返回后必须保持有效...因为strtok返回指向字符串内正确位置的指针,它不会复制令牌.将指针传递到您希望结果结束的空间,并在函数内创建该空间(具有正确的大小),然后将结果复制到其中,这是正确的做法.这一切都非常微妙.如果不清楚,请告诉我!