簡體   English   中英

在C中用%20替換空格

[英]Replacing spaces with %20 in 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 *,作為函數的實際參數。 我嘗試在空間替換塊中的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';
qstr[i] = '%'; qstr[i + 1] = '2'; qstr[i + 2] = '0'; 

該行將三個字符寫入輸出緩沖區,因此您編寫的下一個字符需要寫入qstr [i + 3]。 但是,您只需逐步減1,因此下一個字符將寫入qstr [i + 1],覆蓋'2'。

您需要保留單獨的索引來逐步執行qryqstr

我同意大衛的觀點。

建議分兩步執行:在第一個循環中,您只需計算空格:

int spaceCounter=0;
const int sourceLen = strlen(qry);
for(int i = 0; i < sourceLen; ++i) 
    if ( qry[i] == ' ')
        ++spaceCounter;

char* newString = (char*)malloc(sourceLen + 3*spaceCounter*sizeof(char) + 1)
//check for null!
for(int i = 0; i < sourceLen; ++i) 
    if ( qry[i] == ' ')
    {
        *newString++ = '%';
        *newString++ = '2';
        *newString++ = '0';
    }
    else
        *newString++ = qry[i];

*newString = '\0';

警告:代碼未經過測試。

您使用相同的計數器分配我需要有2個計數器,因為字符串具有不同的長度

你的其他案例指定qstr [i] = qry [i]; 寫完%20后,你在結果字符串上至少減去2。

這稱為url編碼。 您可以參考此頁面查看類似的實現: http//www.geekhideout.com/urlcode.shtml

char* toHexSpace(const char *s)
{
  char *b=strcpy(malloc(3*strlen(s)+1),s),*p;
  while( p=strchr(b,' ') )
  {
    memmove(p+3,p+1,strlen(p));
    strncpy(p,"%20",3);
  }
  return b; 
}

在呼叫上下文中需要“免費”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM