函数 —— 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[]="hello@boy@this@is@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[]="hello@boy@this@is@heima";

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

    printf("%s ",temp);

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

    {

        printf("%s ",temp);

    }

return0;

}

执行结果:

 hello

boy

this

is

heima

猜你喜欢

转载自blog.csdn.net/weixin_42167759/article/details/81123096