C语言字符串操作
一、字符串初始化
[c]
# include <stdio.h>
# include <string.h>
main(){
char str1[4] = "abc";
char str2[4] = {'a', 'b', 'c', '\0'};
printf("%s\n%s\n", str1, str2);
}
[/c]
二、字符串赋值
[c]
# include <stdio.h>
# include <string.h>
main(){
char str[4];
strcpy(str, "abc");
printf("%s\n", str);
}
[/c]
三、字符指针赋值
[c]
# include <stdio.h>
# include <string.h>
main(){
char *str;
str = "abc";
printf("%s\n", str);
}
[/c]
四、连接字符串
[c]
#include <stdio.h>
#include <string.h>
int main ()
{
// strcpy 覆盖原字符串头部
// strcat 往字符串空白部分添加
char str[80];
strcpy(str, "these ");
strcpy(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");
printf("%s\n", str);
return 0;
}
[/c]
五、分割字符串
[c]
#include <stdio.h>
#include <string.h>
main(){
// strtok 第一个参数先是待分割字符串,然后是 NULL
char s[] = "ab-cd : ef;gh :i-jkl;mnop;qrs-tu: vwx-y;z";
char *delim = ":";
char *p;
printf("%s ", strtok(s, delim));
while((p = strtok(NULL, delim)))
printf("%s\n", p);
}
[/c]
六、字符串首次出现位置
[c]
#include<stdio.h>
#include<string.h>
int main(){
char *str = "http://see.xidian.edu.cn/cpp/u/xitong/";
char *substr = "see";
char *s = strstr(str, substr);
printf("%s\n", s);
return 0;
}
[/c]