字符串函数总结
1、搜索子字符函数strchr()
函数原型
char *strchr(const char *str, int c)
参数
str-- 要被检索的 C 字符串。
c-- 在 str 中要搜索的字符。
功能
在参数str所指向的字符串中搜索第一次出现字符c(一个无符号字符)的位置。
返回值
返回一个指向该字符串中第一次出现的字符的指针,如果字符串中不包含该字符则返回NULL空指针。 [2]
头文件
#include <string.h>
例子如下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char *str="wohaoshuai";
char c='s';
char *p;
p=strchr(str,c);
if(p!=NULL){
puts(p);
}
system("pause");
return 0;
}
2、搜索字符串函数strstr
函数原型:
1
extern char *strstr(char *str1, const char *str2);
语法:
1
- strstr(str1,str2)
str1: 被查找目标 string expression to search.
str2: 要查找对象 The string expression to find.
返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。
例子如下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char *str1="wohaoshuai";
char *str2="hao";
char *p=NULL;
p=strstr(str1,str2);
if(p!=NULL){
puts(p);
}
system("pause");
return 0;
}
3、把字符转换成小写函数strlwr
原型:extern char *strlwr(char *s);
用法:#include <string.h>
功能:将字符串s参数转换为小写形式
说明:只转换s参数中出现的大写字母,不改变其它字符。返回指向s参数的指针。
兼容性说明:strlwr和strupr不是标准C库函数,只能在VC中使用。linux gcc环境下需要自行定义这个函数。
注意在windows环境下!!! 把字符串定义为数组形式,char s[ ]=“ASD”;,不要用char *p=“ASD”
例子如下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char s[]="ABCD";
char *p=NULL;
p=strupr(s);
printf("%s\n",p);
system("pause");
return 0;
}
4、把字符串转换成大写函数strupr
原型:extern char *strupr(char *s);
功能:将字符串s转换为大写形式
注意:不能使用常量指针作为参数
说明:只转换s中出现的小写字母,不改变其它字符。返回指向s的指针。
例子如下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char s[]="abcd";
char *p=NULL;
p=strupr(s);
printf("%s\n",p);
system("pause");
return 0;
}
5、分割字符串函数strtok char *strtok(char s[], const char *delim);
分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符(如果传入字符串,则传入的字符串中每个字符均为分割符)。首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
例子如下
如果要获取分隔符前面的字符串只需调用一次函数即可
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char s[]="ABCD,abcd";
char *p=NULL;
p=strtok(s,",");
printf("分隔符前面:%s\n",p);
system("pause");
return 0;
}
运行结果 分隔符前面:ABCD
如果需要在分隔符后面的字符串就需要再调用一次函数,但是需要把目标函数设置成NULL
例子如下
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char s[]="ABCD,abcd";
char *p=NULL;
p=strtok(s,",");
p=strtok(NULL,",");
printf("分隔符后面:%s\n",p);
system("pause");
return 0;
}
运行结果
分隔符后面:abcd