C++中用于操作字符串的很多很多函数
使用前先倒入头文件 #include<cstring>
- strcpy(s1, s2);
复制字符串 s2 到字符串 s1。 - strcat(s1, s2);
连接字符串 s2 到字符串 s1 的末尾。 - strcmp(s1, s2);
如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0。 - strchr(s1, ch);
返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。 - strstr(s1, s2);
返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。 - strlen(s1);
返回字符串 s1 的长度。
上代码:
上结果:
strcpy(str3,str1):hello
strcat(str1,str2):helloworld
strlen(str1):10
C++中提供的string类类型更加牛🍺。不仅支持以上的所有操作还增加了新的功能
上代码:
12 #include<iostream>
13 #include<string>
14 using namespace std;
15 int main()
16 {
17 string str1="hello";
18 string str2="world";
19 string str3;
20 int len;
21 str3=str1;
22 cout<<"str3:"<<str3<<endl;
23 str3=str1+str2;
24 cout<<"str1+str2:"<<str3<<endl;
25 len=str3.size();
26 cout<<"str3.size():"<<len<<endl;
27 return 0;
28 }
输出结果:
str3:hello
str1+str2:helloworld
str3.size():10