C++/C++11中std::string
用法汇总
在C++/C++11中,std::string
是标准库中用于处理字符串的类,它提供了丰富的功能和方法。以下是 std::string
的常见用法汇总:
1. 包含头文件
使用 std::string
前需要包含 <string>
头文件。
#include <string>
2. 声明和初始化
#include <iostream>
#include <string>
int main() {
// 默认构造函数
std::string s1;
// 使用字符串字面量初始化
std::string s2 = "Hello";
std::string s3("World");
// 重复字符初始化
std::string s4(5, 'A'); // "AAAAA"
// 从另一个字符串初始化
std::string s5(s2);
std::cout << s2 << " " << s3 << std::endl;
std::cout << s4 << std::endl;
std::cout << s5 << std::endl;
return 0;
}
3. 字符串拼接
#include <iostream>
#include <string>
int main() {
std::string s1 = "Hello";
std::string s2 = " World";
// 使用 + 运算符拼接
std::string s3 = s1 + s2;
// 使用 += 运算符拼接
s1 += s2;
std::cout << s3 << std::endl;
std::cout << s1 << std::endl;
return 0;
}
4. 字符串长度
#include <iostream>
#include <string>
int main() {
std::string s = "Hello";
// 使用 length() 或 size() 方法获取长度
std::cout << "Length: " << s.length() << std::endl;
std::cout << "Size: " << s.size() << std::endl;
return 0;
}
5. 访问字符串中的字符
#include <iostream>
#include <string>
int main() {
std::string s = "Hello";
// 使用 [] 运算符访问字符
std::cout << s[0] << std::endl;
// 使用 at() 方法访问字符
std::cout << s.at(1) << std::endl;
return 0;
}
6. 字符串比较
#include <iostream>
#include <string>
int main() {
std::string s1 = "Hello";
std::string s2 = "World";
// 使用 == 运算符比较
if (s1 == s2) {
std::cout << "Equal" << std::endl;
} else {
std::cout << "Not equal" << std::endl;
}
// 使用 compare() 方法比较
int result = s1.compare(s2);
if (result == 0) {
std::cout << "Equal" << std::endl;
} else if (result < 0) {
std::cout << "s1 is less than s2" << std::endl;
} else {
std::cout << "s1 is greater than s2" << std::endl;
}
return 0;
}
7. 字符串查找
#include <iostream>
#include <string>
int main() {
std::string s = "Hello World";
// 使用 find() 方法查找子字符串
size_t pos = s.find("World");
if (pos != std::string::npos) {
std::cout << "Found at position: " << pos << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
8. 字符串截取
#include <iostream>
#include <string>
int main() {
std::string s = "Hello World";
// 使用 substr() 方法截取子字符串
std::string sub = s.substr(6, 5); // 从位置6开始,截取5个字符
std::cout << sub << std::endl;
return 0;
}
9. 字符串替换
#include <iostream>
#include <string>
int main() {
std::string s = "Hello World";
// 使用 replace() 方法替换子字符串
s.replace(6, 5, "Universe");
std::cout << s << std::endl;
return 0;
}
10. 字符串删除
#include <iostream>
#include <string>
int main() {
std::string s = "Hello World";
// 使用 erase() 方法删除子字符串
s.erase(6, 5);
std::cout << s << std::endl;
return 0;
}
11. 字符串转换
#include <iostream>
#include <string>
int main() {
// 数字转字符串
int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl;
// 字符串转数字
std::string str2 = "456";
int num2 = std::stoi(str2);
std::cout << num2 << std::endl;
return 0;
}
以上是 std::string
的常见用法,这些方法可以帮助你在C++中高效地处理字符串。