重複の可能性:
C++ での文字列の分割
区切り記号を使用して単一の文字列オブジェクトを個別の文字列に分割し、個々の文字列を出力しようとしています。
例: 入力文字列は、firstname,lastname-age-occupation-telephone です。
「-」文字は区切り記号であり、文字列クラス関数のみを使用して個別に出力する必要があります。
これを行う最良の方法は何ですか?.find を理解するのに苦労しています。substr および同様の関数。
ありがとう!
重複の可能性:
C++ での文字列の分割
区切り記号を使用して単一の文字列オブジェクトを個別の文字列に分割し、個々の文字列を出力しようとしています。
例: 入力文字列は、firstname,lastname-age-occupation-telephone です。
「-」文字は区切り記号であり、文字列クラス関数のみを使用して個別に出力する必要があります。
これを行う最良の方法は何ですか?.find を理解するのに苦労しています。substr および同様の関数。
ありがとう!
getline
文字列がストリーミングされ、読みやすいコードになると思います。
#include <string>
#include <sstream>
#include <iostream>
std::string s = "firstname,lastname-age-occupation-telephone";
std::istringstream iss(s);
for (std::string item; std::getline(iss, item, '-'); )
{
std::cout << "Found token: " << item << std::endl;
}
ここではstring
メンバー関数のみを使用しています。
for (std::string::size_type pos, cur = 0;
(pos = s.find('-', cur)) != s.npos || cur != s.npos; cur = pos)
{
std::cout << "Found token: " << s.substr(cur, pos - cur) << std::endl;
if (pos != s.npos) ++pos; // gobble up the delimiter
}
私はこのようなことをします
do
{
std::string::size_type posEnd = myString.find(delim);
//your first token is [0, posEnd). Do whatever you want with it.
//e.g. if you want to get it as a string, use
//myString.substr(0, posEnd - pos);
myString = substr(posEnd);
}while(posEnd != std::string::npos);