复制字符串的子部分

标签 c string memcpy strcpy

我正在尝试将一个字符串的一部分复制到另一个字符串中。 我知道开始和结束子字符串的 2 个标识符。

我正在尝试从此字符串复制 IP:

0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection

字符串的开头将是“主机:”或 192 结尾将是“\r\nC”或“\r\n”的第二次出现 所以期望的输出是:

192.168.1.200

我尝试使用 strcpy 和 memcpy,但 IP 必须是可变的,所以我不知道它会持续多长时间或会是多少,最少为 11 个字符,最多为 15 个字符。

我希望你能进一步帮助我。

最佳答案

您将需要一个 16 字节的缓冲区(每个八位字节最多 3 个字节,总共 12 个,加上三点是 15,加上零终止符)。

然后,正如您所说,您需要精确定位您的阅读:

host = strstr(string, "Host: ");
if (!host) {
    // Problem. Cannot continue, the string has not the format expected.
}
host += strlen("Host: ");
end  = strstr(host, "\r\n");
if (!end) {
    // Problem
}
// Sanity check: end - host must be less than 16. Someone could send you
// Host: 192.168.25.12.Hello.I.Am.Little.Bobby.Headers\r\n
if ((end - host) > 15) {
    // Big problem
}
// We now know where the address starts, and where it ends.
// Copy the string into address
strncpy(address, host, (end-host));
// Add zero terminator to make this a C string
address[end-host] = 0x0;

关于复制字符串的子部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730403/

相关文章:

c - 将值从静态 char 数组分配给动态分配的 char 数组

c - 是否可以将一段共享内存变成私有(private)内存?

c - 在字符串操作中使用 DI 寄存器

c - 使用char指针模仿c中的strcpy函数

C++ 字符串 : is there good way to replace a char inside a string

Java 递归删除格式中的内容

c - 将 char* 解析为标记时出现段错误

C破解: replace printf to collect output and return complete string by using a line buffer

string - 在 Erlang 中如何检查许多字符串是否不为空?

mysql - C Realloc 追加字符串 MySQL 连接器