在 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++ 的平臺。