C++ string类提供构造、赋值、访问、查找、替换等丰富操作,通过实例演示了长度获取、子串提取、内容替换等功能,并推荐使用stringstream或reserve提升大量字符串拼接效率,同时介绍string::npos用于表示查找失败,以及stoi/to_string等函数实现字符串与数值转换。

C++
string
解决方案
C++
string
string s;
string s = "hello";
string s(n, 'a');
string s(another_string);
s = "world";
s.assign("C++");s.assign(another_string);
s.assign(n, 'b');
s[i]
s.at(i)
s.length()
s.size()
s.capacity()
s.reserve(n)
s.shrink_to_fit()
s += "!";
s.append(" more");s.push_back('c');s.insert(pos, "new");
s.insert(pos, another_string);
s.insert(pos, n, 'x');
s.erase(pos, len);
s.clear()
s.replace(pos, len, "replacement");
s.replace(pos, len, another_string);
s.find("substring");string::npos
s.rfind("substring");s.find_first_of("chars");s.find_last_of("chars");s.substr(pos, len);
s1 == s2
s1 != s2
s1 < s2
s1 > s2
s.compare(another_string);
s.c_str()
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 长度
std::cout << "Length: " << str.length() << std::endl;
// 查找
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::cout << "'World' found at position: " << pos << std::endl;
}
// 子串
std::string sub = str.substr(7, 5); // "World"
std::cout << "Substring: " << sub << std::endl;
// 替换
str.replace(7, 5, "C++");
std::cout << "Replaced string: " << str << std::endl;
return 0;
}使用
+=
append
stringstream
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::stringstream ss;
for (int i = 0; i < 1000; ++i) {
ss << "Number: " << i << " ";
}
std::string result = ss.str();
std::cout << result.substr(0, 100) << "..." << std::endl; // 输出部分结果
return 0;
}使用
stringstream
reserve
string::npos
string::npos
string
-1
size_t
find
string::npos
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
size_t pos = str.find("World");
if (pos == std::string::npos) {
std::cout << "'World' not found in the string." << std::endl;
} else {
std::cout << "'World' found at position: " << pos << std::endl;
}
return 0;
}string
int
float
C++11 提供了
std::stoi
std::stof
std::stod
std::to_string
#include <iostream>
#include <string>
int main() {
std::string str_int = "123";
std::string str_float = "3.14";
int num_int = std::stoi(str_int);
float num_float = std::stof(str_float);
std::cout << "Integer: " << num_int << std::endl;
std::cout << "Float: " << num_float << std::endl;
std::string new_str_int = std::to_string(num_int * 2);
std::string new_str_float = std::to_string(num_float * 2);
std::cout << "New Integer String: " << new_str_int << std::endl;
std::cout << "New Float String: " << new_str_float << std::endl;
return 0;
}需要注意的是,如果字符串不能正确转换为数值类型,
std::stoi
std::stof
std::stod
以上就是C++ string类操作 常用字符串处理方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号