天天看點

函數 —— strtok() 例如:按照字元拆分字元串,放入新定義的數組中;按照字元拆分字元串,放入原先的數組中

問題描述:

原始數組:char str[80] = "This is - aa bb - cc - dd";

新定義的數組:     char newstr[80]=  {0};

分割符号:    const char s[2] = "-";

1、把原始數組中的字元串str,按照分割符号“-”,拆分後,再重組,放入新定義的數組newstr中:

     即:把 str , 按照“-”符号規則 分割,重組後放入newstr

#include <string.h>
#include <stdio.h>
int main()
{
	char str[80] = "This is - aa bb - cc - dd";
	const char s[2] = "-";
	printf("str=%s\n",str);
	char *token = (strtok(str,s));
	char cont[80]=  {0};
	char newstr[80]=  {0};
	while(token)
	{
		sprintf(cont,"%s",token);
		printf("count=%s\n",token);
		token = strtok(NULL,s);
		strcat(newstr,cont);
	}
	printf("newstr=%s\n",newstr);
	return 0;
}
           
執行結果

str=This is - aa bb - cc - dd

count=This is 

count= aa bb 

count= cc 

count= dd

newstr=This is  aa bb  cc  dd

2、把原始數組中的字元串str,按照分割符号“-”,拆分後,再重組,放入原始的數組str中:

     即:把 str , 按照“-”符号規則 分割,重組後放入str

#include <string.h>
#include <stdio.h>
int main()
{
	char str[80] = "This is - aa bb - cc - dd";
	const char s[2] = "-";
	char cont[80]=  {0};
	char ss[80]=  {0};
	char *token = (strtok(str,s));
	while(token)
	{
		sprintf(cont,"%s",token);
		printf("count = %s\n",token);
		token = strtok(NULL,s);
		strcat(ss,cont);
	}
	printf("ss = %s\n",ss);
	printf("str = %s\n",str);
	memset(str,0,strlen(str));
	//strcat(str,ss);   
	sprintf(str,"%s",ss); //或者
	printf("after strcat str = %s\n",str);
	return 0;
}
           
執行結果

count = This is 

count =  aa bb 

count =  cc 

count =  dd

ss = This is  aa bb  cc  dd

str = This is 

after strcat str = This is  aa bb  cc  dd

3、分割字元串的兩種方式

strtok() :

分解字元串為一組字元串。s為要分解的字元串,delim為分隔符字元串。

例如:

#include<stdio.h>

#include<string.h>

int main(void)

{

    char buf[]="[email protected]@[email protected]@heima";

    char*temp = strtok(buf,"@");

    while(temp)

    {
        printf("%s ",temp);

        temp = strtok(NULL,"@");
    }

return0;

}
           

執行結果:       

hello

boy

this

is

heima

#include<stdio.h>

#include<string.h>

int main(void)

{

    char buf[]="[email protected]@[email protected]@heima";

    char*temp = strtok(buf,"@");

    printf("%s ",temp);

    while((temp = strtok(NULL,"@")))

    {

        printf("%s ",temp);

    }

return0;

}
           

執行結果:

 hello

boy

this

is

heima

繼續閱讀