解析字符数组
Parsing char array
我有一个字符数组如下:
char* test = "+IPD,308:{data:\"abc\"} UNLINK";
我试图将它解析为 return 从 {
到 }
的块,所以在这种情况下子字符串 {data:\"abc\"}
.
我使用了 strchr()
和 strrchr()
,其中 return 是指向单个字符位置的指针;但在这种情况下,我将如何使用它来 return {data:\"abc\"}
?
您可以尝试遍历字符串。当您到达第一个标记时,开始将字符复制到第二个缓冲区中。到达第二个标记时跳出循环。
试试这个:
const char* input = "+IPD,308:{data:\"abc\"} UNLINK";
char* start = strchr(input, '{'); // result should be input[9]
char* end = strrchr(input, '}'); // result should be input[20]
char* output = (char*)malloc(end-start+2); // End-start should be 11 + 2 = 13
strncpy(output, start, end-start+1); // Copy 12 chars.
output[end-start+1] = '[=10=]'; // Append an End-of-String nul
/* Use the output string.... */
free(output); // Very important cleanup!
output = NULL;
它找到第一个大括号,最后一个大括号,分配适当的内存,然后strncpy
用相关数据创建一个新字符串。
IDE Link: http://ideone.com/sVn147
输出:{data:"abc"}
我有一个字符数组如下:
char* test = "+IPD,308:{data:\"abc\"} UNLINK";
我试图将它解析为 return 从 {
到 }
的块,所以在这种情况下子字符串 {data:\"abc\"}
.
我使用了 strchr()
和 strrchr()
,其中 return 是指向单个字符位置的指针;但在这种情况下,我将如何使用它来 return {data:\"abc\"}
?
您可以尝试遍历字符串。当您到达第一个标记时,开始将字符复制到第二个缓冲区中。到达第二个标记时跳出循环。
试试这个:
const char* input = "+IPD,308:{data:\"abc\"} UNLINK";
char* start = strchr(input, '{'); // result should be input[9]
char* end = strrchr(input, '}'); // result should be input[20]
char* output = (char*)malloc(end-start+2); // End-start should be 11 + 2 = 13
strncpy(output, start, end-start+1); // Copy 12 chars.
output[end-start+1] = '[=10=]'; // Append an End-of-String nul
/* Use the output string.... */
free(output); // Very important cleanup!
output = NULL;
它找到第一个大括号,最后一个大括号,分配适当的内存,然后strncpy
用相关数据创建一个新字符串。
IDE Link: http://ideone.com/sVn147
输出:{data:"abc"}