smitz
smitz

Reputation: 59

string from after the second space character

I have a string

string str= "Jhon 12345 R333445 3434";
string str1= "Mike 00987 #F54543";    

So from str i want "R333445 3434" only because after second space character whatever appear i want all, similarly form str1 "#F54543"

I used stringstream and extract the next word after the space but it wont give correct result for

str ="Jhon 12345 R333445 3434";

it gives R333445 only it should give "R333445 3434"

Please suggest some better logic of my problem.

Upvotes: 0

Views: 9388

Answers (3)

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20823

How about

#include <string>
#include <iostream>

int main()
{
  const std::string str = "Jhon 12345 R333445 3434";

  size_t pos = str.find(" ");
  if (pos == std::string::npos)
    return -1;

  pos = str.find(" ", pos + 1);
  if (pos == std::string::npos)
    return -1;

  std::cout << str.substr(pos, std::string::npos);
}

Output

 R333445 3434

According to http://ideone.com/P1Knbe.

Upvotes: 2

Dr.Tower
Dr.Tower

Reputation: 995

You could find the index of the second space and then take the substring from one position past it to the end.

int index = 0;
for (int i = 0; i < 2; ++i){
    index = (str.find(" ", index)) + 1;
}

ans = str.substr(index);

reference on std::string::find

reference on std::string::substr

Upvotes: 2

stardust
stardust

Reputation: 5988

It seems you want to skip the first two words and read the rest, if that is correct you can do something like this.

std::string str("Jhon 12345 R333445 3434"");
std::string tmp, rest;

std::istringstream iss(str);
// Read the first two words.    
iss >> tmp >> tmp;
// Read the rest of the line to 'rest'
std::getline(iss,rest);
std::cout << rest;

Upvotes: 2

Related Questions