c語言 字符串的拼接和分割實例
1.字符串的拼接
使用c的函數(shù)char *strcat(char *str_des, char *str_sou);
將字符串str_sou接在字符串str_des后面(放在str_des的最后字符和“\0”之間)。
注意不要越界,可用strlen(input)函數(shù)求字符串長度之后再拼接。
2. 字符串的分割
使用c的函數(shù) char *strtok(char *str_sou,constchar *str_sep);
str_sou:待分割字符串。str_sep:分割符號。
第一次調(diào)用:temp = strtok(input, a);(input:字符串,a:分隔符);
之后調(diào)用: temp = strtok(NULL, a);
temp為分割后得到的字符串。
3. demo
#include <string.h>
#include <stdio.h>
int main(void)
{
char input[16];
//拼接,a:分割符號;b,c:2個字符串
char *a = ":", *b = "1", *c = "我是qy";
printf("拼接前的字符串(亂碼):%s\n",input); //input 沒有初始化,打印的是亂碼
strcpy(input,b);
strcat(input,a);
strcat(input,c);
printf("拼接后的字符串:%s\n",input);
// 長度:printf("拼接后的字符串的長度: %d\n",strlen(input));
char *temp;
temp = strtok(input, a);
if (temp)
printf("分割符號前的字符串 : %s\n", temp);
temp = strtok(NULL, a);
if (temp)
printf("分割符號后的字符串 : %s\n",temp);
return 0;
}
以上這篇c語言 字符串的拼接和分割實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

