C++中string字符串的基础操作,学习

string 字符串

常用函数

  • substring()
  • string.length()&&string.size()
  • string.find()
  • string.replace()
  • string.substr()

string初始化和声明

#include<bits/stdc++.h>
using namespace std;
	int main(){
        string str1; //空字符串
        string str2="hello, world";  //注意中间有空格和‘,’逗号
        //通过str2赋值给str3
        string str3=str2; 
        //初始化重复的字母
        stirng str4(5,'C'); // str4="CCCCC"
        return 0;       
    }

获取字符串的长度

string.length()&&string.size()

#include<bits/stdc++.h>
using namespace std;
	int main(){
       string str1="hello,, world";
        int len=str1.length();
        int len1=str1.size();
        cout<<len<<len1; //输出13 包括2个逗号和一个空格
        return 0;       
    }

length()size()返回的是无符号整数(0,1,2...) 使用时尽量用 (int)str1.length()进行强转

字符串查找

string.find()

#include<bits/stdc++.h>
using namespace std;
	int main(){
       string str1="hello,, world";
       int x=str1.find(" world"); //用int 替代 size_t (无符合整数)
	   cout<<x; //输出7 空格的下标是7
       int y=str1.find(" 2world");
       cout<<y;//输出的-1;
             
    }

找到相应的子串会返回子串中第一个char在字符串中的下标,如果没有找到会返回 -1

字符串拼接

+ || append()

#include<bits/stdc++.h>
using namespace std;
	int main(){
       string str1="hello";
       string str2="world"
       string str3(5,'Z');
       // 用+进行拼接
       string re1=str1+str2+str3;
       cout<<re1; //输出helloworldZZZZZ
       //用append()
       string re2=str1.append(str2).append(str3).append("!");
       cout<<re2; //输出helloworldZZZZZ!
    }

**+ 拼接时可用char拼接,但在append()中的参数只能是string类型,不能是char **

string re1=str1+str2+str3+'!'+"2313";
cout<<re1;//输出helloworldZZZZZ!2313
string re2=str1.append(str2).append(str3).append('!');//append('!')会报错

字符串替换

string.replace()

#include<bits/stdc++.h>
using namespace std;
	int main(){
       string str1="hello,, world";
       str1.replace(7,3,"333444");//7代表从下标为7的元素开始‘ ’,3代表要替换的长度(” wo“)
       cout<<str1;//输出 hello,,333444rld
    }

提取子字符串

substr()

#include<bits/stdc++.h>
using namespace std;
	int main(){
       string str1="hello,, world";
       string re1=str1.substr(2,4); //2表示从下标2开始,4表示提取子字符串的长度;
       cout<<re1;//输出 llo,
    }

字符串比较

compare()

#include<bits/stdc++.h>
using namespace std;
	int main(){
       string str1="hello,,world";
       string str2="heooll";
       int in=str1.compare(str2); // 比较到下标为2时,'l'<'o' 所以返回-1
       cout<<in;//输出-1 str1比str2小
       
       // 用<,>,== 来比较字符串大小
       int re1=str1<str2;
       int re2=str1==str2;
       int re3=str1>str2;
       cout<<re1<<re2<<re3;//输出 1 0 0
        
    }

字符串的比较不是越长就越大,比较时会从第一个元素进行一一对应的比较,如果有不相同的元素就会马上得出结果;

re=str1.compare(str2)

  • re==0 字符串相等
  • re<0 str1较小
  • re>0 str2较大

用 <,>,== 比较 re=str1<str2

  • re=1 str1小于str2
  • re=0 str1不小于str2
posted @ 2024-11-10 20:28  zpa666  阅读(105)  评论(0)    收藏  举报