在C中用%20替换空格

Nil*_*esh 4 c http

我正在为我的网站写一个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];
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*vid 16

String-handling in C can be tricky. I'd suggest going through the string first, counting the spaces, and then allocating a new string of the appropriate size (original string size + (number of spaces*2)). Then, loop through the original string, maintaining a pointer (or index) to the position in both the new string and the original one. (Why two pointers? Because every time you encounter a space, the pointer into the new string will get two characters ahead of the pointer into the old one.)

Here's some code that should do the trick:

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';
Run Code Online (Sandbox Code Playgroud)

  • 如果速度优于内存,则使用3倍于原始字符串空间的字符串,并跳过搜索空格以确定新字符串的长度.就像在Kangkan的回答链接中找到的方法一样. (2认同)

Jam*_*ran 6

qstr[i] = '%'; qstr[i + 1] = '2'; qstr[i + 2] = '0'; 
Run Code Online (Sandbox Code Playgroud)

该行将三个字符写入输出缓冲区,因此您编写的下一个字符需要写入qstr [i + 3].但是,您只需逐步减1,因此下一个字符将写入qstr [i + 1],覆盖'2'.

您需要保留单独的索引以便单步执行qry&qstr.