目录
字符串的长度
下面为大家介绍几种有关字符串长度的求法。
string a="Hello,world";
cout<<a.size();
string a="Hello,world";
cout<<a.length();
注:strlen需要头尾间<string.h>
char a[]="Hello,world";
cout<<strlen(a);
这三个函数的返回值都为11。
1.strcmp
如果str1的长度>str2的长度则返回-1;如果str1的长度<str2的长度则返回1;如果str1==str2的长度则按字典序排列,若两个字符串完全相等则返回0。
注:strcmp需要头文件<string.h>
char str1[]="Hello,world";
char str2[]="world";
cout<<strcmp(str1,str2)<<endl;
字符与字符串
2.strchr
strchr是查找一个字符在字符串中首次的位置并返回它的指针。如果字符串中不包含该字符则返回NULL。
注:strchr需要头文件<string.h>
char a[]="Hello,world";
char *q=strchr(a,'o');
cout<<q-a+1<<endl;
3.strrchr
strrchr是查找一个字符在字符串中首次的位置并返回它的指针。如果字符串中不包含该字符则返回NULL。
注:strrchr需要头文件<string.h>
char a[]="Hello,world";
char *q=strrchr(a,'o');
cout<<q-a+1<<endl;
字符串与字符串
4.strstr
strstr是查找一个字符串在另一个字符串中首次出现的位置并返回他的指针。如果被查找字符串中不包含该字符串则返回NULL。
注:strstr需要头文件<string.h>
char a[]="Hello,world";
char *q=strstr(a,"world");
cout<<q-a+1<<endl;
5.strcat
C库函数strcat()函数的功能是实现字符串的拼接。示例如下。
注:strcat需要头文件<string.h>
char a[1000]="Hello",b[100]=",world";
strcat(a,b);
printf("%s\n",a);
return 0;
值得注意的是被连接的字符串总长度必须要满足两个字符串的总空间。
6.strcspn
strcspn是返回字符串str1中连续n个不含字符串str2中字符的字符数。
注:strcspn需要头文件<string.h>
char str1[]="Hello,world";
char str2[]="world";
cout<<strcspn(str1,str2)<<endl;
7.strxfrm
strxfrm是将str1的前x个字符替换成str2的前x个字符。
注:strxfrm需要头文件<string.h>
char str1[]="Hello,world";
char str2[]="world";
int x=2;
strxfrm(str1,str2,x);
printf("%s\n",str1);
8.strspn
strspn是返回str1中第一个不是str2中存在的字符的下标。
注:strspn需要头文件<string.h>
char str1[]="wrozd,Hello";
char str2[]="world";
cout<<strspn(str1,str2);
9.strpbrk
strpbrk返回一个指针,指向str2中任意一个字符第一次在str1中出现的位置,不存在则返回NULL。
注:strpbrk需要头文件<string.h>
char str1[]="Hello,world";
char str2[]="world";
char *p=strpbrk(str1,str2);
cout<<p-str1+1;
10.substr
substr返回从指定位置到字符串末的字符串。
string a="Hello,world";
string b=a.substr(3);
cout<<b;
11.swap
swap交换两个字符串。
string a="Hello,world";
string b="abc";
swap(a,b);
cout<<a<<endl<<b;
12.rfind
1.rfind(str)
从字符串右端查找另一个字符串首次出现的位置,并返回下标。
string a="Hello,world";
int b=a.rfind("wo");
cout<<b;
2.rfind(str,position)
rfind(str,position)从position开始向前查找首个匹配的字符串。
string a="Hello,wolld";
int b=a.rfind("ll",7);
cout<<b;
若无匹配字符串则返回-1。
13.replace
replace(left,length,str2) 替换掉str1中从left开始的length长度的字符串为str2,多出str2的长度则删除str1中对应多出的字符。
string a="llHello,wolld";
string b="abcde";
a.replace(5,6,b);
cout<<a;
字符大小写问题
14.tolower和toupper
tolower大写转小写,toupper小写转大写。
若不是52个大小写字符,或大写转大写,或小写转小写则返回原字符。
char a=tolower('A'),b=toupper('b'),c=toupper('1');
cout<<a<<" "<<b<<" "<<c;
字符串空间存储
15.reserve与capacity与resize
capacity()函数返回在重新申请更多的空间前字符串可以容纳的字符数. 这个数字至少与字符串长度一样大。
reserve(num)函数保留本个字符串num个空间。
resize()函数改变本字符串的大小到num, 新空间的内容不确定。也可以指定用指定字符填充。
感谢大家的阅读,如有问题请联系作者修改。