C++で文字列を分割する方法は何ですか?
C++で文字列をサブ文字列に分割する方法はいくつかあります。以下は一般的な方法の例です。
- 動詞の「翻訳する」は英語で”translate”という意味です。
- 標準::getline
- 文字列を操作する標準ライブラリの一部であるstringstream
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main() {
std::string str = "Hello,World,Example,String";
std::stringstream ss(str);
std::vector<std::string> tokens;
std::string token;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
for (const auto& elem : tokens) {
std::cout << elem << std::endl;
}
return 0;
}
- 見つける
- 部分文字列
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string str = "Hello,World,Example,String";
std::vector<std::string> tokens;
std::string delimiter = ",";
size_t pos = 0;
while ((pos = str.find(delimiter)) != std::string::npos) {
std::string token = str.substr(0, pos);
tokens.push_back(token);
str.erase(0, pos + delimiter.length());
}
tokens.push_back(str);
for (const auto& elem : tokens) {
std::cout << elem << std::endl;
}
return 0;
}
これらの方法は具体的な状況に応じて選択して使用することができます。区切り文字が異なれば、コード内の区切り文字パラメータを調整することができます。