C++中用于操作字符串的很多很多函数

使用前先倒入头文件 #include<cstring>

  1. strcpy(s1, s2);
    复制字符串 s2 到字符串 s1。
  2. strcat(s1, s2);
    连接字符串 s2 到字符串 s1 的末尾。
  3. strcmp(s1, s2);
    如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0。
  4. strchr(s1, ch);
    返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。
  5. strstr(s1, s2);
    返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。
  6. strlen(s1);
    返回字符串 s1 的长度。

上代码:

C++ 之字符串一家亲

上结果:

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
 

相关文章:

  • 2021-11-08
  • 2021-10-14
  • 2022-12-23
  • 2021-10-15
  • 2021-08-21
猜你喜欢
  • 2021-07-31
  • 2022-12-23
  • 2021-09-25
  • 2022-02-02
  • 2021-11-19
相关资源
相似解决方案