开发者

CString Parsing Carriage Returns

Let's say I have a string that has multiple carriage returns in it, i.e:

394968686

10063038开发者_运维百科2

395950966

335666021

I'm still pretty amateur hour with C++, would anyone be willing to show me how you go about: parsing through each "line" in the string ? So I can do something with it later (add the desired line to a list). I'm guessing using Find("\n") in a loop?

Thanks guys.


while (!str.IsEmpty())
{
    CString one_line = str.SpanExcluding(_T("\r\n"));
    // do something with one_line
    str = str.Right(str.GetLength() - one_line.GetLength()).TrimLeft(_T("\r\n"));
}

Blank lines will be eliminated with this code, but that's easily corrected if necessary.


You could try it using stringstream. Notice that you can overload the getline method to use any delimeter you want.

string line;
stringstream ss;
ss << yourstring;
while ( getline(ss, line, '\n') )
{
  cout << line << endl;
}

Alternatively you could use the boost library's tokenizer class.


You can use stringstream class in C++.

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
   string str = "\
                394968686\
                100630382\
                395950966\
                335666021";
   stringstream ss(str);
   vector<string> v;

   string token;
   // get line by line
   while (ss >> token)
   {
      // insert current line into a std::vector
      v.push_back(token);
      // print out current line
      cout << token << endl;
   }
}

Output of the program above:

394968686
100630382
395950966
335666021

Note that no whitespace will be included in the parsed token, with the use of operator>>. Please refer to comments below.


If your string is stored in a c-style char* or std::string then you can simply search for \n.

std::string s;
size_t pos = s.find('\n');

You can use string::substr() to get the substring and store it in a list. Pseudo code,

std::string s = " .... ";
for(size_t pos, begin = 0; 
    string::npos != (pos = s.find('\n'));
    begin = ++ pos)
{
  list.push_back(s.substr(begin, pos));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜