C语言分割字符串

我有这样一个字符串:"bizbox_username=admin; bizstore_note=; bizbox_userlang=zh; csd=33; cod=29.30; business_note=null",我想通过C语言的分割,得到bizbox_userlang的值,比如这里的zh,然后我会根据这个值来做不同的操作。我自己写了一段,写不下去了,初学,望高手帮忙!!!感谢!!!
这是我写的一段:
#include <stdio.h>
#include <string.h>

void main()
{
char buf1[]="bizbox_username=admin; bizbox_userpass=c1501f6698e058e47d3f81f723c2b9f2; bizstore_note=; bizbox_userlang=zh; csd=33; cod=29.30; business_note=null";
char* token = strtok( buf1, " ");
while( token != NULL )
{
printf( "%s\n", token );
token = strtok( NULL, " ");
}
}
这样可以得到按空格分割的字符串,比如bizbox_username=admin;,下面该怎么继续啊!
一楼的意思是再用一次strtok函数来用=分割吧,这样感觉比较麻烦,还有别的思路吗?

使用strtok函数即可实现分割字符串。

1、strtok函数:
原型:char *strtok(char s[], const char *delim);
功能:将一个字符串分解为一组字符串,s为要分解的字符串,delim为分隔符字符串;
说明:当strtok函数在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针;
头文件:string.h;
返回值:从字符串s开头开始的一个个被分割的字符串。分割结束时,返回NULL。所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。
2、例程:

#include<stdio.h>
#include<string.h>
int main(){
    char input[16]="abc,d,ef,g";//待分解字符串
    char* delim=",";//分隔符字符串
    char* p=strtok(input,delim);//第一次调用strtok
    while(p!=NULL){//当返回值不为NULL时,继续循环
        printf("%s\n",p);//输出分解的字符串
        p=strtok(NULL,delim);//继续调用strtok,分解剩下的字符串
    }
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-08-04
#include <stdio.h>
#include <string.h>
int main()
{
char buffer[]="bizbox_username=admin; bizbox_userpass=c1501f6698e058e47d3f81f723c2b9f2; bizstore_note=; bizbox_userlang=zh; csd=33; cod=29.30; business_note=null";
char str[50];
char *p1=buffer,*p2;
int i;
while((p1=strchr(p1,'='))!=NULL)
{
p2=strchr(p1,';');
for(i=0,p1++;p1!=p2;p1++)
str[i++]=*p1;
str[i]='\0';
printf("%s\n",str);
}
return 0;
}
第2个回答  推荐于2017-09-30
使用strstr函数嘛(以下代码测试通过)
功能:在一个字符串中查找特定的字符串,如果查找到会返回查找到字符串的位置,失败返回NULL
分析:搜索字符串"bizbox_userlang=",成功后取出'='后和‘=’后第1个';'之间的所有字符

#include <stdio.h>
int main(int argc, char* argv[])
{
char buf1[]="bizbox_username=admin; bizbox_userpass=c1501f6698e058e47d3f81f723c2b9f2; bizstore_note=; bizbox_userlang=zh; csd=33; cod=29.30; business_note=null";
char *buf2="bizbox_userlang=";
char *ptr;
char txt[100];

ptr=strstr(buf1,buf2); //成功返回的位置是"bizbox_userlang=zh; csd=33...."
if( ptr==NULL)
{
printf("没有找到该内容\n");
return -1;
}
ptr=ptr+strlen(buf2); //向后移动要查找字符串的长度,返回的位置是"zh; csd=33...."
int i=0;
while(*ptr!=';') //把'='和';'之间的字符记录在txt[]数组中
{
txt[i]=*ptr;
ptr+=1;
i=i+1;
}
txt[i]='\0';//字符串末尾记得补0
printf("你要查找的内容是: %s\n", txt);

system("pause");

return 0;
}本回答被提问者采纳
第3个回答  2010-08-04
再以“=”为分隔符字符串进行查找不可以吗?
相似回答