我有一个字符串的形式
"http://something.another.thing:13541/random-text.txt"
我想提取 "something.another.thing:13541"
的一部分,所以我用
sscanf(uri, "http://%s/%*s", host);
将指定的部分读入缓冲区 host
. %*s
应该忽略字符串中在 /
对吗?
问题不在于丢弃部分,你需要一个定界符。[^?]
试试
char *uri = "http://something.another.thing:13541/random-text.txt";
char host[266];
sscanf(uri, "http://%265[^/]", host); // %265 prevents buffer overflows
printf("%s\n", host);
由于一个主机不能包含超过255个字节+比如10个端口。char host[266];
是你想要覆盖所有可能的情况。
另一个选择是用 getconf HOST_NAME_MAX
并将其传递给程序,如果你在一些linux下。