Parsing a string

◀ Random Number Generator▶ Conversion Between char* and string
Amazon This function has been covered in-depth by Chapter 12.8, but in case you miss it, let me introduce to you this useful function again. If you have information stored in one single string, separated by a delimiter, you can write a function to parse the string and retrieve relevant data. For example, you can have the following string representing a person’s bank account information, with # being the delimiter:
[email protected]#Amr#99999.99#”
The first substring is the person’s id; the second one is the person’s birthday; the third one is the person’s account type; the fourth one is the person’s email address; the fifth one is the person’s login password; the sixth one is the person’s current balance.


I want to write a function that takes as arguments a string, like the one in the above example, and an index (starting at 1, not 0), specifying which substring to return. The delimiter the function uses is #. The function returns a string which is the substring specified by the index. Now you can start writing this function on your own as an exercise. Here is my version:
#include<iostream>
using namespace std;
#include<string>  /* or <string.h> */

string parse(string s, int i) {
string t=""; int counter=0; bool start=false; for(int j=0;j<s.length();j++) { if(s[j]=='#') counter++; if(!start&&counter==i-1) start=true; if(counter==i) break; if(start&&s[j]!='#') t+=s[j]; } return t; }
However, if you know C++ string class very well, you probably know you can take advantage of some of the functions it provides such as find(). Here is another version of the function that utilizes C++ string functions:
#include<iostream>
using namespace std; #include<string> /* or <string.h> */ string parse(string s, int i) { if(i<1) return ""; int d, second, first, pos; pos=first=0; for(d=0;d<i-1;d++) { first=s.find('#',pos); if(first==string::npos) return ""; pos=first+1; } second=s.find('#',pos); if(first==0) first=-1; return s.substr(first+1,second-first-1); }
◀ Random Number Generator▶ Conversion Between char* and string

fShare
Questions? Let me know!