[英]Breaking the string into parts in C
自從我用C語言編寫程序以來,我有一個類似下面的字符串
"VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, plan 1, assa=784617896.9649164, plan24, massmedua=plan12, masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan"
我需要在“=”之前得到那些,即VRUWFB02,VRUWFB01,assa,massmedua,masspedia。
我能夠打破字符串,但無法提取那些特定的單詞。
誰能幫我這個
char st[] = "VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, plan 1,assa=784617896.9649164, plan24, massmedua=plan12, masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan";
char *ch;
regex_t compiled;
char pattern[80] = " ";
printf("Split \"%s\"\n", st);
ch = strtok(st, " ");
while (ch != NULL) {
if(regcomp(&compiled, pattern, REG_NOSUB) == 0) {
printf("%s\n", ch);
}
ch = strtok(NULL, " ,");
}
return 0;
這是我用來解釋事情的快速示例程序:
#include <string.h>
#include <stdio.h>
int main(void)
{
char s[] = "VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, "
"plan 1, assa=784617896.9649164, plan24, massmedua=plan12, "
"masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan";
char *p;
char *q;
p = strtok(s, " ");
while (p)
{
q = strchr(p, '=');
if (q)
printf("%.*s\n", (int)(q - p), p);
p = strtok(NULL, " ");
}
return 0;
}
並輸出:
$ ./example
VRUWFB02
VRUWFB01
assa
massmedua
masspedia
基本思想是用空格分割字符串,然后在塊中查找=
字符。 如果顯示,則打印該塊的所需部分。
您可以使用strtok函數來破壞字符串。 您可以在我參考的網頁上找到使用它的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.