用C有20%的空间更换 [英] Replacing spaces with %20 in C

查看:142
本文介绍了用C有20%的空间更换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写我的网站C. FastCGI应用程序不要问为什么,留一个组成部分。

I am writing a fastcgi application for my site in C. Don't ask why, leave all that part.

就帮我这个problem-我想和20%,以取代在查询字符串空间。
这里的code我用,但我没有看到20在输出中,只有%。哪里的问题?

Just help me with this problem- I want to replace spaces in the query string with %20. Here's the code I'm using, but I don't see 20 in the output, only %. Where's the problem?

code:

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];
  }
}

在code,QRY为char *,是作为一个实际参数的功能。
我试着用我的realloc()在空间替代块+ 3,4,5,没有成功。

In the code, qry is char *, comes as a actual parameter to the function. I tried with i + 3, 4, 5 in realloc() in the space replacer block, no success.

推荐答案

字符串处理用C可能会非常棘手。我想通过字符串建议去首先,计数空格,然后分配适当大小的一个新的字符串(原始字符串大小+空格(数* 2))。然后,通过原串循环,保持一个指针(或索引)的位置在这两个新的字符串和原之一。 (为什么两个指针?因为每次你遇到一个空间,指针进入新的字符串将提前获得指针到老一两个字符)。

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.)

下面是一些code,它应该做的伎俩:

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';

这篇关于用C有20%的空间更换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆