string的使用
string的声明与初始化
读入字符串可用==getline(cin, s)== cin >> s
int main(){
//声明并初始化一个空字符串
string str1;
//使用字符串字面量初始化字符串
string str2 = "Hello Word!";
//使用另一个string对象来初始化字符串
string str3 = str2;
//使用部分字符串初始化字符串
string str4 = str2.substr(0, 5);//substr(起始位置,长度)
//使用字符数组初始化字符串
const char* charArray = "Hello";
string str5(charArray);
//使用重复的字符初始化字符串
string str5(5, A);
//输出字符串
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
cout << str4 << endl;
cout << str5 << endl;
cout << str6 << endl;
return 0;
}
空 |
---|
Hello Word |
Hello Word |
Hello |
Hello |
AAAAA |
各种基本操作
获取字符串长度(length/size)
string str = "Hello Word!";
int length = str.length();
//或者int length = str.size();
cout << "length: " << length << endl;
拼接字符串(+或append)
string str1 = "Hello";
string str2 = "Word!";
result = str1 + "," + str2;//使用 + 运算符
result = str1.append(",").append(str2);//使用append函数
cout << result1 << endl;
cout << result2 << endl;
字符串查找
string str = "hello word!";
size_t pos = str.find("word");//查找子字符串的位置
if(pos != string :: nops){
cout << pos << endl;
}else{
cout << "not found" << endl;
}
字符串替换(replace)
string str = "hello word";
str.replace(7, 5, "Universe");
// 替换子字符串,7 表示起始位置,5 表示长度
cout << "result: " << str << endl;
提取子字符串
string str = "hello word!";
string substr = str.substr(7, 5);//提取子字符串
cout << substr << endl;
字符串比较(compare)
string str1 = "hello";
string str2 = "word!";
int result = str1.compare(str2);//比较字符串
if(result == 0){
cout << "string are equal." << endl;}
else if(result < 0){
cout << "string is less than string 2." << end;;
}else {
cout << "string is greater than string 2." << endl;
}
各种基本操作
常用的遍历string的方法有两种:
- 循环枚举下标
- auto枚举(其中&表示取引用类型, 如果对i修改将会改变原来的值)
string s = "hello";
for(int i = 0; i < s.length(); ++i) cout << s[i] << end1;
for(auto i : s){
cout << i;
i = 'a';//此处的修改无效,因为这个i是拷贝出来的,而不是引用s的
} cout << '\n';
for(auto &i : s)
{
cout << i;
i = 'a'//此处修改会改变s的字符值
}
cout << '\n';//此时s = "aaaaa"
cout << s << endl;
输出 |
---|
hello |
hello |
hello |
aaaaa |