parsing particular part of a string in c++
Question
I have a vector of strings that i read from the output of a command, the format of the output is, that contains key and ip values.
key: 0 165.123.34.12
key: 1 1.1.1.1
key1: 1 3.3.3.3
I need to read the values of the keys as 0,1,1 and the ips for each key. Which string function can i use?
Solution
Here is a simple solution for C++:
const char *data[] = {"key: 0 165.123.34.12", "key: 1 1.1.1.1", "key1: 1 3.3.3.3"};
vector<string> vstr(data, data+3);
for (vector<string>::const_iterator i=vstr.begin() ; i != vstr.end() ; ++i) {
stringstream ss(*i);
string ignore, ip;
int n;
ss >> ignore >> n >> ip;
cout << "N=" << n << ", IP=" << ip << endl;
}
On ideone: link.
OTHER TIPS
Use rfind
and substr
.
First find the first ' '
's index from the right. That will be the end of your substring. Next, find the previous one.
Take the substring between the two indexes.
If the string has trailing spaces, you'll need to trim those beforehand.
code removed
sscanf()
is very useful:
char* s = "key: 14 165.123.34.12";
int key_value;
char ip_address[16];
if (2 == sscanf(s, "%*[^:]: %d %15s", &key_value, ip_address))
{
printf("key_value=%d ip_address=[%s]\n", key_value, ip_address);
}
Output:
key_value=14 ip_address=[165.123.34.12]
The format specifier "%*[^:]"
means read to the first colon but don't assign to any variable.