问题描述
我必须在C中解析此字符串:
I have to parse this string in C:
XFR 3 NS 207.46.106.118:1863 0 207.46.104.20:1863\r\n
并能够获得207.46.106.118
部分和1863
部分(第一个IP地址).
And be able to get the 207.46.106.118
part and 1863
part (the first ip address).
我知道我可以逐个字符地查找字符,并最终找到解决方法,但是,鉴于字符串中的IP地址可以更改为其他格式(数字较少),获得该信息的最简单方法是什么? /p>
I know I could go char by char and eventually find my way through it, but what's the easiest way to get this information, given that the IP address in the string could change to a different format (with less digits)?
推荐答案
您可以使用C标准库中的sscanf()
.这是一个如何以字符串形式获取IP和端口的示例,假设地址前面的部分是恒定的:
You can use sscanf()
from the C standard lib. Here's an example of how to get the ip and port as strings, assuming the part in front of the address is constant:
#include <stdio.h>
int main(void)
{
const char *input = "XFR 3 NS 207.46.106.118:1863 0 207.46.104.20:1863\r\n";
const char *format = "XFR 3 NS %15[0-9.]:%5[0-9]";
char ip[16] = { 0 }; // ip4 addresses have max len 15
char port[6] = { 0 }; // port numbers are 16bit, ie 5 digits max
if(sscanf(input, format, ip, port) != 2)
puts("parsing failed");
else printf("ip = %s\nport = %s\n", ip, port);
return 0;
}
格式字符串的重要部分是扫描集模式%15[0-9.]
和%5[0-9]
,它们将匹配由数字或点组成的最多15个字符的字符串(即,不会检查ip地址的格式是否正确) )和最多5个数字的字符串(这意味着2 ^ 16-1以上的无效端口号将通过).
The important parts of the format strings are the scanset patterns %15[0-9.]
and %5[0-9]
, which will match a string of at most 15 characters composed of digits or dots (ie ip addresses won't be checked for well-formedness) and a string of at most 5 digits respectively (which means invalid port numbers above 2^16 - 1 will slip through).
这篇关于在C语言中解析字符串的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!