Search in a string and go to next one.

May 16, 2011 at 1:49pm
How do i repeat in string find?

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string textout;
  size_t pos;

string test = "User=1234 User=5678 User=12345";

  pos = test.find("User");
  textout = test.substr (pos, 9);
  
  cout << textout; // This will only output first User, if i want next one? tried a "while" function but it only repeated the first search. 

system("PAUSE");

  return 0;
}
Last edited on May 16, 2011 at 2:03pm
May 16, 2011 at 2:10pm
There is another way to call find, in which you tell it where in the string to start looking. It is up to you to keep track of where you have already looked.

http://www.cplusplus.com/reference/string/string/find/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string textout;
  size_t pos = 0;
  

string test = "User=1234 User=5678 User=12345";

pos = test.find("User", pos);
  textout = test.substr (pos, 9);
  cout << textout << endl; 
  pos = test.find("User", pos+9);
  textout = test.substr (pos, 9);
  cout << textout << endl; 
  pos = test.find("User", pos+9);
  textout = test.substr (pos, 10);
  cout << textout << endl; 

return 0;
}

Topic archived. No new replies allowed.