C++幅文字列の切り取り例
2221 ワード
ワイド文字列の例:
ヘッダファイル:
実装ファイル:
ワイド文字の使用方法:
通常の文字列の例:
ヘッダファイル:
実装ファイル:
使用方法:
ヘッダファイル:
void WStringSplit( const std::wstring & wstr, std::vector<std::wstring> & tokens, const std::wstring & delimiters);
実装ファイル:
void WStringSplit( const std::wstring & wstr, vector<std::wstring> & tokens, const std::wstring & delimiters)
{
// Skip delimiters at beginning.
std::wstring::size_type lastPos = wstr.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::wstring::size_type pos = wstr.find_first_of(delimiters, lastPos);
while (std::wstring::npos != pos || std::wstring::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(wstr.substr(lastPos, pos - lastPos));
// Skip delimiters.
lastPos = wstr.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = wstr.find_first_of(delimiters, lastPos);
}
}
ワイド文字の使用方法:
std::vector<std::wstring> tokens;
std::wstring urlstr(buffer);
std::wstring delimiter(L"&");
std::wstring tempstr;
WStringSplit(urlstr, tokens, delimiter);
通常の文字列の例:
ヘッダファイル:
void StringSplit( const std::string & str, std::vector<std::string> & tokens, const std::string & delimiters);
実装ファイル:
void StringSplit( const std::string & str, vector<std::string> & tokens, const std::string & delimiters)
{
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters.
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
使用方法:
vector<string> tmp;
StringSplit(str, tmp, ",");
int size = tmp.size();