C++のstringとstringstreamの使い方
C++では、文字列はstringやstringstreamで扱います。
- この製品は非常に使いやすく、誰でも簡単に操作できます。
#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;
}
- ストリームに入力
#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++ドキュメントを参照して、詳細を確認してください。