January 24,2006

separate each space in one string

string str = "1.roger 2.chunag 3.abc 4.ccc";
size_t pos = str.find(" "); // indexof of _first_ space
size_t oldPos = 0;
while (pos != string::npos)
{
string piece = str.substr(oldPos, pos - oldPos);
cout << piece << endl;
oldPos = pos + 1;
pos = str.find(" ", oldPos);
}

out put

1.roger
2.chunag
3.abc
4.ccc



Posted by yam_javanull at 樂多Roodo! │18:03 │回應(4)引用(0)C++
樂多分類:網路/3C 共同主題:程式設計 工具:編輯本文
Ads by Roodo! 

引用URL

http://cgi.blog.roodo.com/trackback/1043715
回應文章
Because the loop only runs until no more space is found.
to output last:


Code:

string str = "1.roger 2.chunag 3.abc 4.ccc";
size_t pos = str.find(" "); // indexof of _first_ space
size_t oldPos = 0;
while (pos != string::npos)
{
string piece = str.substr(oldPos, pos - oldPos);
cout << piece << endl;
oldPos = pos + 1;
pos = str.find(" ", oldPos);
}
cout << str.substr(oldPos) << endl;


It can't be that hard for yourself to read about the string class.
Posted by roger5089 at January 24,2006 18:18
Because at the point when you have processed the "3.abc" segment, you store oldPos = pos + 1.

Then:


Code:
pos = str.find(" ", oldPos)



is searching only on the part of the string: "4.ccc".

There are no spaces in that string, so find() will return string::npos, your loop exits and the program eventually exits.

If you add the following immediately after the closing brace of the while() loop:


Code:
if (pos == string::npos && oldPos != 0) cout << str.substr(oldPos) << endl;


Posted by roger at January 24,2006 23:27
Use replace this method

string str1 = "1.roger 2.chunag 3.abc 4.ccc";
replace(str1.begin(), str1.end(), ' ', '\n');
cout << str1 << endl;
Posted by roger5089 at January 25,2006 13:37
[URL=http://www.vlassio.cn/tel-aviv-cose-fare] tel aviv cose fare [/URL] tel aviv cose fare [URL=http://www.vlassio.cn/fax-cordless] fax cordless [/URL] fax cordless [URL=http://www.vlassio.cn/egizi] egizi [/URL] egizi
Posted by Aria at June 3,2008 15:02