我有一个从命令输出中读取的stringvector,输出的格式是包含key和ip的值。
key: 0 165.123.34.12 key: 1 1.1.1.1 key1: 1 3.3.3.3
我需要读取键的值为0,1,1和每个键的ips。 我可以使用哪个string函数?
这是一个简单的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; }
在ideone: 链接 。
使用rfind
和substr
。
首先从右边找到第一个的索引。 这将是你的子字符串的结尾。 接下来,找到前一个。
取两个索引之间的子串。
如果字符串有尾随空格,则需要事先修剪。
代码已删除
sscanf()
非常有用:
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); }
输出:
key_value = 14 ip_address = [165.123.34.12]
格式说明符"%*[^:]"
表示读取到第一个冒号,但不分配给任何变量。