可能重複的字符串:
Splitting a string in C++分割使用一個分隔符
我想用一個分隔符爲單獨的字符串,然後輸出每個組串拆分一個字符串對象。
e.g輸入的字符串名字,姓氏,年齡,職業,電話
的「 - 」字符是分隔符,我需要輸出他們分別只使用String類的功能。
這樣做的最好方法是什麼?我很難理解.find。 substr和類似的功能。
謝謝!
可能重複的字符串:
Splitting a string in C++分割使用一個分隔符
我想用一個分隔符爲單獨的字符串,然後輸出每個組串拆分一個字符串對象。
e.g輸入的字符串名字,姓氏,年齡,職業,電話
的「 - 」字符是分隔符,我需要輸出他們分別只使用String類的功能。
這樣做的最好方法是什麼?我很難理解.find。 substr和類似的功能。
謝謝!
我會做這樣的事情
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);
'find'需要一個起始位置來通過第一個位置。 – chris
@chris:是的,沒錯。修復它 –
我覺得字符串流和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
}
這種違反使用std :: string成員函數的限制 –
@ArmenTsirunyan:嗯,這是一個恥辱。 –
你可以看看這裏的答案:http://stackoverflow.com/questions/236129/s plitting-a-string-in-c – chris
什麼是你不瞭解的功能?如果我們知道,解釋你不明白的事情會容易得多。 – chris