版权声明:如若转载,请联系作者。 https://blog.csdn.net/liu16659/article/details/88937344
C++中 string 常用的函数
1.compare
函数
1.1 代码
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int main(){
string str1 = "abc";
string str2 = "abc";
string str3 = "abd";
cout << str1.compare(str2) << "\n";
cout << str1.compare(str3) << "\n";
}
2. 执行结果
2. substr()
函数的使用
2.1 代码
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int main(){
string str1 = "Push 309";
cout << str1 << "\n";
cout << str1.substr(5);
}
2.2 执行结果
3.如何添加字符
在C++中,如果要在一个字符串后添加一个字符,可以直接使用+=
即可。
示例如下:
3.1 代码
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int main(){
string res ="My ";
res+= "n";
res+= "a";
res+= "m";
res+= "e";
res+= " is LittleLawson!";
cout << res;
}