我有一个从命令输出中读取的字符串向量,输出格式为,其中包含键和 ip 值。
key: 0 165.123.34.12
key: 1 1.1.1.1
key1: 1 3.3.3.3
我需要将键的值读取为 0,1,1 和每个键的 ips。我可以使用哪个字符串函数?
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.
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]
格式说明符"%*[^:]"
意味着读取到第一个冒号但不分配给任何变量。
使用rfind
和substr
。
' '
首先从右边找到第一个的索引。那将是您的子字符串的结尾。接下来,找到上一个。
取两个索引之间的子字符串。
如果字符串有尾随空格,则需要事先修剪这些空格。
代码已删除