在 CentOS 系统中,C++ 字符串处理通常使用标准库 <string> 中的 std::string 类。以下是一些基本的字符串处理操作示例:
首先,确保包含了 <string> 头文件:
#include <iostream>
#include <string>
std::string str1 = "Hello, World!";
std::string str2 = "CentOS";
可以使用 + 运算符或者 append() 方法进行字符串连接:
std::string str3 = str1 + " Welcome to " + str2;
// 或者使用 append()
std::string str4;
str4.append(str1);
str4.append(" Welcome to ");
str4.append(str2);
使用 length() 或 size() 方法获取字符串长度:
std::cout << "Length of str1: " << str1.length() << std::endl; // 或者 str1.size()
使用 find() 方法查找子字符串的位置:
size_t pos = str1.find("World");
if (pos != std::string::npos) {
std::cout << "Found 'World' at position: " << pos << std::endl;
}
可以使用 replace() 方法进行字符串替换:
str1.replace(7, 5, "CentOS"); // 将 "World" 替换为 "CentOS"
C++ 标准库没有直接提供字符串分割的功能,但可以通过遍历字符串手动实现:
std::string str = "apple,orange,banana";
std::stringstream ss(str);
std::string item;
while (std::getline(ss, item, ',')) {
std::cout << item << std::endl;
}
可以使用 std::stoi(), std::stof(), std::stod() 等函数进行字符串到数值类型的转换:
std::string numStr = "123";
int num = std::stoi(numStr);
使用 std::cin 和 std::cout 进行字符串的输入输出:
std::string input;
std::cout << "Enter a string: ";
std::cin >> input;
std::cout << "You entered: " << input << std::endl;
以下是一个完整的示例程序,演示了上述一些基本操作:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string str1 = "Hello, World!";
std::string str2 = "CentOS";
// 字符串连接
std::string str3 = str1 + " Welcome to " + str2;
std::cout << "Concatenated string: " << str3 << std::endl;
// 字符串长度
std::cout << "Length of str1: " << str1.length() << std::endl;
// 字符串查找
size_t pos = str1.find("World");
if (pos != std::string::npos) {
std::cout << "Found 'World' at position: " << pos << std::endl;
}
// 字符串替换
str1.replace(7, 5, "CentOS");
std::cout << "After replacement: " << str1 << std::endl;
// 字符串分割
std::string str = "apple,orange,banana";
std::stringstream ss(str);
std::string item;
std::cout << "Split string:" << std::endl;
while (std::getline(ss, item, ',')) {
std::cout << item << std::endl;
}
// 字符串转换
std::string numStr = "123";
int num = std::stoi(numStr);
std::cout << "Converted number: " << num << std::endl;
// 字符串输入输出
std::string input;
std::cout << "Enter a string: ";
std::cin >> input;
std::cout << "You entered: " << input << std::endl;
return 0;
}
编译并运行这个程序:
g++ -o string_example string_example.cpp
./string_example
这个示例涵盖了 C++ 中字符串处理的许多基本操作,适用于 CentOS 系统以及其他支持 C++ 的平台。