c - 在 C 中用 %20 替换空格

标签 c http

我正在用 C 为我的站点编写一个 fastcgi 应用程序。不要问为什么,留下所有那部分。

请帮我解决这个问题 - 我想用 %20 替换查询字符串中的空格。 这是我正在使用的代码,但我在输出中看不到 20,只有 %。问题出在哪里?

代码:

unsigned int i = 0;

/*
 * Replace spaces with its hex %20
 * It will be converted back to space in the actual processing
 * They make the application segfault in strtok_r()
 */

char *qstr = NULL;
for(i = 0; i <= strlen(qry); i++) {
  void *_tmp;
  if(qry[i] == ' ') {
    _tmp = realloc(qstr, (i + 2) * sizeof(char));
    if(!_tmp) error("realloc() failed while allocting string memory (space)\n");
    qstr = (char *) _tmp;
    qstr[i] = '%'; qstr[i + 1] = '2'; qstr[i + 2] = '0';
  } else {
    _tmp = realloc(qstr, (i + 1) * sizeof(char));
    if(!_tmp) error("realloc() failed while allocating string memory (not space)\n");
    qstr = (char *) _tmp;
    qstr[i] = qry[i];
  }
}

在代码中,qry是char *,作为函数的实参。 我尝试在空间替换 block 中的 realloc() 中使用 i + 3、4、5,但没有成功。

最佳答案

C 中的字符串处理可能很棘手。我建议先遍历字符串,计算空格,然后分配一个适当大小的新字符串(原始字符串大小 +(空格数 * 2))。然后,循环遍历原始字符串,维护指向新字符串和原始字符串中位置的指针(或索引)。 (为什么是两个指针?因为每次遇到空格时,指向新字符串的指针都会比指向旧字符串的指针提前两个字符。)

下面是一些应该可以解决问题的代码:

int new_string_length = 0;
for (char *c = qry; *c != '\0'; c++) {
    if (*c == ' ') new_string_length += 2;
    new_string_length++;
}
char *qstr = malloc((new_string_length + 1) * sizeof qstr[0]);
char *c1, *c2;
for (c1 = qry, c2 = qstr; *c1 != '\0'; c1++) {
    if (*c1 == ' ') {
        c2[0] = '%';
        c2[1] = '2';
        c2[2] = '0';
        c2 += 3;
    }else{
        *c2 = *c1;
        c2++;
    }
}
*c2 = '\0';

关于c - 在 C 中用 %20 替换空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3424474/

相关文章:

json - GraphQL 和 rest api 有什么区别

node.js - 如何立即关闭 Node.js http(s) 服务器?

c# - 尝试创建 HttpContent 时在 Http post 中抛出 InvalidOperationException

c - 如何使用 setenv 为 bash 数组设置值

c - 我收到以下错误 : "Array subscript is not an integer". 但数组的类型为 int。我做错了什么?

c - 在 Arduino 上每 y 秒执行一次函数 x 秒

Java构造http请求报文

http - 如何处理 TlsNotSupported 并使用 Network.HTTP.Client 调用 HTTPS URL?

C:如何按最小数字对文件进行排序(使用结构)?

c - getnameinfo 指定 socklen_t