函数 —— strtok() 例如:按照字符拆分字符串,放入新定义的数组中;按照字符拆分字符串,放入原先的数组中
生活随笔
收集整理的這篇文章主要介紹了
函数 —— 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? |
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
總結
以上是生活随笔為你收集整理的函数 —— strtok() 例如:按照字符拆分字符串,放入新定义的数组中;按照字符拆分字符串,放入原先的数组中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 读文件 —— WEB前端读取本地文件内容
- 下一篇: 函数 —— memset() 将存放字