在 Linux 中,C++ 可以使用标准库 <string> 和 <cstring> 进行字符串处理。以下是一些常用的字符串处理方法:
#include <iostream>
#include <string>
#include <cstring>
std::string str1 = "Hello, World!";
const char* str2 = "Hello, C++!";
size_t len1 = str1.length();
size_t len2 = strlen(str2);
std::string str3 = str1 + " " + str2;
int result = str1.compare(str2); // 返回负数表示 str1 < str2,0 表示相等,正数表示 str1 > str2
size_t pos = str1.find("World"); // 返回子字符串 "World" 在 str1 中的位置,如果找不到则返回 std::string::npos
std::string str4 = str1.replace(pos, 5, "Linux"); // 将 str1 中从位置 pos 开始的 5 个字符替换为 "Linux"
#include <sstream>
#include <vector>
std::istringstream iss(str1);
std::string word;
std::vector<std::string> words;
while (iss >> word) {
words.push_back(word);
}
int num = std::stoi(str1); // 将字符串 str1 转换为整数
double dbl = std::stod(str1); // 将字符串 str1 转换为浮点数
std::string str5 = std::to_string(num); // 将整数 num 转换为字符串
这些只是 C++ 字符串处理的一部分功能。你可以根据需要使用其他 <string> 和 <cstring> 库中的函数。