在C++中,可以使用string
和stringstream
來處理字符串。
string
類來創建和操作字符串:#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 獲取字符串長度
std::cout << "Length: " << str.length() << std::endl;
// 獲取子字符串
std::string subStr = str.substr(0, 5);
std::cout << "Substring: " << subStr << std::endl;
// 連接字符串
std::string concatStr = str + " Welcome!";
std::cout << "Concatenated string: " << concatStr << std::endl;
// 查找字符串
std::size_t found = str.find("World");
if (found != std::string::npos) {
std::cout << "Found at index: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
stringstream
類來處理字符串流:#include <iostream>
#include <sstream>
int main() {
std::string str = "42 3.14 Hello";
std::istringstream iss(str); // 從字符串創建輸入流
int num;
float fNum;
std::string word;
// 從流中提取數據
iss >> num >> fNum >> word;
std::cout << "Number: " << num << std::endl;
std::cout << "Float Number: " << fNum << std::endl;
std::cout << "Word: " << word << std::endl;
std::ostringstream oss; // 創建輸出流
oss << "Concatenated: " << num << " " << fNum << " " << word;
std::cout << oss.str() << std::endl; // 輸出流中的字符串
return 0;
}
這是一些簡單的示例,string
和stringstream
類還有更多的功能和用法,可以根據具體需求查閱C++文檔來了解更多信息。