在CentOS系統中,C++字符串處理主要依賴于標準庫中的<string>
頭文件。以下是一些常用的C++字符串處理技巧:
創建和初始化字符串:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello, World!";
std::string str2(5, 'a'); // 創建一個長度為5,每個字符都是'a'的字符串
return 0;
}
連接字符串:
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string str3 = str1 + str2; // str3現在是"Hello, World!"
獲取字符串長度:
std::string str = "Hello, World!";
size_t length = str.length(); // 或者使用str.size()
訪問字符串中的字符:
std::string str = "Hello, World!";
char c = str[0]; // 獲取第一個字符,即'H'
查找子字符串:
std::string str = "Hello, World!";
size_t pos = str.find("World"); // 查找"World"的位置,返回一個size_t類型的值
if (pos != std::string::npos) {
std::cout << "Found at position: " << pos << std::endl;
}
替換子字符串:
std::string str = "Hello, World!";
size_t pos = str.find("World");
if (pos != std::string::npos) {
str.replace(pos, 5, "CentOS"); // 將"World"替換為"CentOS"
}
分割字符串:
#include <sstream>
#include <vector>
std::string str = "apple,orange,banana";
std::stringstream ss(str);
std::string item;
std::vector<std::string> tokens;
while (std::getline(ss, item, ',')) {
tokens.push_back(item);
}
去除字符串兩端的空白字符:
#include <algorithm>
#include <cctype>
std::string str = " Hello, World! ";
str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](int ch) {
return !std::isspace(ch);
}));
str.erase(std::find_if(str.rbegin(), str.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), str.end());
字符串轉換:
#include <string>
#include <sstream>
std::string str = "12345";
int num;
std::stringstream ss(str);
ss >> num; // 將字符串轉換為整數
double pi = 3.14159;
std::stringstream pi_ss;
pi_ss << pi;
std::string pi_str = pi_ss.str(); // 將浮點數轉換為字符串
這些技巧可以幫助你在CentOS系統中使用C++進行字符串處理。根據具體需求,你可以靈活運用這些方法。