在c++中解析字符串的特定部分
parsing particular part of a string in c++
我有一个从命令输出中读取的字符串向量,输出的格式为,包含键值和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;
}
在表意文字上:链接。
使用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.12.34.12]
格式说明符"%*[^:]"
表示读取第一个冒号,但不分配给任何变量。
相关文章:
- ODBC:如何将空字符串绑定到C 中的空
- CodeBlocks字符串输出定界线
- 尝试将字符串传递到绑定的函数C
- 使用C 从定界线拆分字符串中提取整数数组
- Node-ffi 绑定到 NULL 终止的 C 字符串数组,但得到“分段错误:11”
- 字符串文字绑定到一个非常量字符指针
- 在字符串上迭代,但将定界器保持在子字符串中,包括其他规则
- 将char*绑定到字符串
- 如何函数<void(字符串消息)>绑定到成员函数?
- Sample.exe中0x7537812f处未处理的异常:0xC0020001:字符串绑定无效
- 浏览字符串并将部分行读取到类字段中
- Clang:将绑定或mem_fn与字符串::c_str和转换一起使用时出现问题
- 代码合成XSD解析/数据绑定xml字符串,而不是xml文件
- 使用带有绑定的boost字符串算法谓词
- 增强绑定和分配以将矢量转换为字符串
- 在c++中使用递归解除字符串的绑定
- C++如何创建"绑定"字符串文本替换方法?
- 从文件中读取字符串并将其不同部分保存在C++中的不同变量中
- 绑定密钥?(c)(将字符串转换为函数)
- 将C++_TCHAR绑定到SWIG接口中的C#字符串