String manipulation

Write your question here.
Can somebody help explain to me how to do string manipulation using substr() or find()? I feel like it is simple and I'm just over thinking it.
1
2
  string substr, f, l;
  string line = "F=John, L=Smith, V=3342";
So you want to end up with f="John" and l="Smith" ?
What is it that you want to achieve Marcus99?
int x = line.find("John"); //look for it, and save the index where it is if found.
string sub = line.substr(x,4); //we know its there, but if it were not you need to check x vs string::npos to see if it was found or not..

john is 4 long, so extract 4 chars to make the substring.

slightly more interesting, then..

x = line.find("V=");
if(x != string::npos)
cout << line.substr(x+2,4); //maybe we know V= but not the code number value
else
cout << "bad input" << endl;


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;


vector<string> split( const string &line, const char delimiter = ',' )
{
   vector<string> result;
   stringstream ss( line );
   for ( string word; getline( ss >> ws, word, delimiter ); ) result.push_back( word );
   return result;
}

 
int main()
{
   string test = "F=John, L=Smith, V=3342";
   vector<string> names = split( test );              // split by comma

   cout << "Stage 1 split:\n";
   for ( string s : names ) cout << s << '\n';

   cout << "\nStage 2 split:\n";
   for ( string nm : names )
   {
      vector<string> parts = split( nm, '=' );              // split at =
      for ( string s : parts ) cout << s << "  ";
      cout << '\n';
   }
}




Stage 1 split:
F=John
L=Smith
V=3342

Stage 2 split:
F  John  
L  Smith  
V  3342 
Topic archived. No new replies allowed.