C ++で文字列を分離する方法、または任意の文字に基づいて切り取る方法を紹介します。
1. substr() で文字列を切り捨てる
substr() は、文字列の Index から目的の長さの文字列を切り捨て、文字列として返します。
substrのSyntaxは次のようになります。引数としてインデックスと長さを受け取り、文字列を返します。
string substr (size_t pos = 0, size_t len = npos) const;次の例は、文字列の特定の部分を切り捨てるコードです。 substr(0, 5) は、Index 0 で始まる 5 つの文字を切り取り、文字列として返します。
substr(6, 5) は、Index 6 から長さ 5 の文字列を切り捨てて返します。
#include <iostream>
#include <string>
int main () {
std::string str = "Hello World, C++";
std::string newstr1 = str.substr(0, 5);
std::string newstr2 = str.substr(6, 5);
std::string newstr3 = str.substr(13, 3);
std::cout << newstr1 << std::endl;
std::cout << newstr2 << std::endl;
std::cout << newstr3 << std::endl;
return 0;
}Output:
Hello
World
C++substring(6)のようにIndexだけを引数として渡し、長さは渡さないと文字列の最後まで切り捨てます。
以下のように、 substr(6) は Index 6 から文字列の最後まで切り捨てられ、文字列として返されます。 substr(13) は Index 13 から文字列の最後まで切り捨てて返します。
#include <iostream>
#include <string>
int main () {
std::string str="Hello World, C++";
std::string newstr1 = str.substr(6);
std::string newstr2 = str.substr(13);
std::cout << newstr1 << std::endl;
std::cout << newstr2 << std::endl;
return 0;
}Output:
World, C++
C++2. substr() と find() で文字列を分離する
find(separator, index) は引数として渡されたIndexからセパレータを探し、そのIndexを返します。 separatorがない場合はnposを返します。
以下の例は、 find() と substr() を使って , に基づいて文字列を分離する例です。
文字列「Hello、World、C ++」は、以下のコードで「Hello」、「World」、「C ++」に分割されています。
動作原理は、while内で文字列の :を探し、 substr()で :の直前まで文字列を切り捨てることです。
#include<iostream>
#include<string>
int main() {
std::string str = "Hello,World,C++";
std::string separator = ",";
int cur_position = 0;
int position;
while ((position = str.find(separator, cur_position)) != std::string::npos) {
int len = position - cur_position;
std::string result = str.substr(cur_position, len);
std::cout << result << std::endl;
cur_position = position + 1;
}
std::string result = str.substr(cur_position);
std::cout << result << std::endl;
}Output:
Hello
World
C++3. getline() と istringstream で文字列を分離する
getline() と istringstream を使って、上記のように区切り文字で文字列を分離できます。
文字列をistringstreamに変換し、 getline()を介して区切り文字に基づいて文字列を読み取ることができます。
#include<iostream>
#include<string>
#include<sstream>
int main() {
std::string str = "Hello,World,C++";
char separator = ',';
std::istringstream iss(str);
std::string str_buf;
while (getline(iss, str_buf, separator)) {
std::cout << str_buf << std::endl;
}
return 0;
}Output:
Hello
World
C++