在c++中解析字符串的特定部分

parsing particular part of a string in c++

本文关键字:定部 字符串 c++      更新时间:2023-10-16

我有一个从命令输出中读取的字符串向量,输出的格式为,包含键值和ip值。

key:  0 165.123.34.12
key:  1 1.1.1.1
key1: 1 3.3.3.3

我需要将键的值读取为0,1,1,并读取每个键的ips。我可以使用哪个字符串函数?

这里有一个简单的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;
}

在表意文字上:链接。

使用rfindsubstr

首先从右边找到第一个' '的索引。这将是子字符串的末尾。接下来,找到上一个。

取两个索引之间的子字符串。

如果字符串有尾随空格,则需要事先修剪这些空格。

代码删除

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.12.34.12]

格式说明符"%*[^:]"表示读取第一个冒号,但不分配给任何变量。