在 Linux 下使用 C++ 进行字符串处理,通常会用到 C++ 标准库中的 <string> 头文件。这个头文件提供了一系列用于操作字符串的类和函数。以下是一些基本的字符串处理操作:
包含头文件:
#include <iostream>
#include <string>
创建字符串:
std::string str = "Hello, World!";
获取字符串长度:
size_t length = str.length(); // 或者使用 str.size();
连接字符串:
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string str3 = str1 + str2; // str3 现在是 "Hello, World!"
查找子字符串:
size_t found = str.find("World"); // 返回子字符串 "World" 在 str 中的位置
if (found != std::string::npos) {
std::cout << "Substring found at position: " << found << std::endl;
}
替换子字符串:
size_t pos = str.find("World");
if (pos != std::string::npos) {
str.replace(pos, 5, "Linux"); // 将 "World" 替换为 "Linux"
}
分割字符串:
分割字符串通常需要自己实现,因为 <string> 库没有直接提供分割功能。下面是一个简单的分割函数示例:
#include <vector>
#include <sstream>
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// 使用示例
std::vector<std::string> parts = split(str, ' ');
for (const auto& part : parts) {
std::cout << part << std::endl;
}
转换字符串:
int num = std::stoi("1234");
std::string strNum = std::to_string(1234);
输入输出:
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "!" << std::endl;
这些是 C++ 字符串处理的一些基本操作。根据你的具体需求,可能还需要使用其他 <string> 库中的功能或者结合正则表达式库 <regex> 来进行更复杂的字符串处理。