CodersSC
CodersSC

Reputation: 710

Getting Strings which are multiple lines

Here i have a string which is split and each line is in a different cell in a vector and i want to retrieve all of the line if the first three letters are .N/ however it seems that i can only retrieve one of the lines which start with .N/ below is the string which i am working with.

std::string message = ".N/1TLIS/PART/123456789I/A/1234RFGH67323\n"
    ".N/AT0931/2DEC/GVA/Y\n"
    ".I/KL0967/02APR/AMS/F\n"
    ".O/123/MARRIOTT/27MAY/084512L//FEDEXVAN45\n";

CODE WHICH I USE AT THE MOMENT

std::vector<std::string> el; //VECTOR
    split(el,message,boost::is_any_of("\n"));// the string above is split line for line into vector el

 for(int i = 0; i < el.size(); i++)
     {
         if(el[i].substr(0,3) == ".N/")
         {

             str = el[i].substr(3);

         }
     }
     cout << str;

However when i print out str i only get "1TLIS/PART/123456789I/A/1234RFGH67323" and not 1TLIS/PART/123456789I/A/1234RFGH67323 and "AT0931/2DEC/GVA/Y"

Is there a way where i can retrieve all lines starting which a specific character?

Upvotes: 0

Views: 259

Answers (3)

nabulke
nabulke

Reputation: 11285

Another alternative solution using algorithms:

#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>

using namespace std;

ostream_iterator<string> out_it(cout, "\n");

remove_copy_if(el.begin(), el.end(), out_it, 
    !boost::bind(boost::algorithm::starts_with<string, string>, _1, ".N/"));

Upvotes: 2

Kristofer
Kristofer

Reputation: 3279

You need to append to str, currently you are just replacing, try: First initialize str with "" before the for loop, then inside the for loop

str.append(el[i].substr(3));

Upvotes: 0

shengy
shengy

Reputation: 9749

for(int i = 0; i < el.size(); i++)
{
    if(el[i].substr(0,3) == ".N/")
    {

        str = el[i].substr(3);
        cout << str << endl;
    }
}

str is overwritten at every time you found ".N/", and you just outputed the last one.

Upvotes: 0

Related Questions