簡體   English   中英

編寫一個方法來替換C樣式字符串中的所有空格

[英]Write a method to replace all spaces in a C style string

我遇到過這個面試問題,並希望在嘗試理解其解決方案時提供一些幫助:

編寫一個方法來用'%20'替換字符串中的所有空格。

解決方案(來自論壇):

char str[]="helo b";
int length = strlen(str);
int spaceCount = 0, newLength, i = 0;

for (i = 0; i < length; i++) {
if (str[i] == ' ') {
    spaceCount++; //count spaces...
}
}

newLength = length + spaceCount * 2;   //need space for 2 more characters..
str[newLength] = '\0';

for (i = length - 1; i >= 0; i--) {
    if(str[i] == ' ') {
        str[newLength - 1] = '0'; //???
        str[newLength - 2] = '2';
        str[newLength - 3] = '%';
        newLength = newLength - 3;
    } else {
        str[newLength - 1] = str[i];
        newLength = newLength - 1;
    }
}

這個程序對我不起作用...我首先想在深入研究代碼之前先了解算法。

那個樣本壞了。

緩沖區溢出,字符串的一個無意義掃描(strlen),難以閱讀。

int main() {
  char src[] = "helo b";
  int len = 0, spaces = 0;
  /* Scan through src counting spaces and length at the same time */
  while (src[len]) {
    if (src[len] == ' ')
      ++spaces;
    ++len;
  }
  /* Figure out how much space the new string needs (including 0-term) and allocate it */
  int newLen = len + spaces*2 + 1;
  char * dst = malloc(newLen);
  /* Scan through src and either copy chars or insert %20 in dst */
  int srcIndex=0,dstIndex=0;
  while (src[srcIndex]) {
    if (src[srcIndex] == ' ') {
      dst[dstIndex++]='%';
      dst[dstIndex++]='2';
      dst[dstIndex++]='0';
      ++srcIndex;
    } else {
      dst[dstIndex++] = src[srcIndex++];
    }
  }
  dst[dstIndex] = '\0';
  /* Print the result */
  printf("New string: '%s'\n", dst);
  /* And clean up */
  free(dst);
  return 0;
}
for (i = 0; i < length; i++) {
    if (str[i] == ' ') {
        spaceCount++; //count spaces...
    }
}

由於我們用三個字符替換單個字符(''),我們首先計算空間數以計算大小增加。

newLength = length + spaceCount * 2;   //need space for 2 more characters..
str[newLength] = '\0';

這不可能這樣做, 你必須分配更多的內存 ,但在這里我們擴展了字符串變量的大小。 我認為最好是分配一個新變量,因為下一步將更容易與另一個變量。

for (i = length - 1; i >= 0; i--) {
    if(str[i] == ' ') {
        str[newLength - 1] = '0'; //???
        str[newLength - 2] = '2';
        str[newLength - 3] = '%';
        newLength = newLength - 3;
    } else {
        str[newLength - 1] = str[i];
        newLength = newLength - 1;
    }
}

最后,如果字符串被正確擴展,這是步驟應該工作,但它可以稍微重寫以更清楚。

我建議這樣的事情,假設newstr是我們在先前步驟中分配的新變量:

int j = 0;
for(i = 0; i < length; i++, j++) {
   if(str[i] == ' ') {
      newstr[j] = '%';
      newstr[++j] = '2';
      newstr[++j] = '0';
   } else {
      newstr[j] = str[i];
   }
}

或者,如果要保留向后循環(不需要使用此循環分配另一個字符串):

for (i = length - 1, j = newLength - 1; i >= 0; i--, j--) {
    if(str[i] == ' ') {
        str[j] = '0';
        str[--j] = '2';
        str[--j] = '%';
    } else {
        str[j] = str[i];
    }
}

算法是這樣的:首先計算空格數...說字符串是“ae rt”,這意味着2個空格..當前長度為6(如果索引為0,則為5)輸出字符串應該是“ae%20r%20t”..長度= 10(在索引= 0的情況下為9)所以新的長度是6 +'2'* 2所以她來到10 ......

這個長度如何調整..然后他從反向遍歷並逐個字符地放置......當他遇到空格時,他將%20反向放置,因為他以相反的順序遍歷原始字符串...

/* program to replace the space with "%20" */
/* Author senthilkumar M */

eg str = "ab cd ef"
   str1 = "ab%20cd%20ef"


char *space_replace(char *str)
{
        int l = strlen(str);
        int i = 0, j =0;
        int spc = 0, nl = 0;
        char *str1 = NULL;

        for(i = 0; i < l; i++)  {
                if(str[i] == ' ') {
                        spc++;
                }
        }
        nl = l + 2*spc + 1;
        str1 = (char *) malloc(sizeof(char) * nl);
        if(!str1) {
                fprintf(stdout, "malloc failed \n");
                return NULL;
        }
        for(i = 0; i < l; i++) {
                if(str[i] == ' ') {
                        str1[j++] = '%';
                        str1[j++] = '2';
                        str1[j++] = '0';
                } else {`enter code here`
                        str1[j++] =  str[i];
                }
        }
        str1[j] = '\0';
        return str1;
}

正如我所看到的,它首先搜索字符串以查找所有空格,然后它嘗試延長字符串以適應字符串中每個空格的2個額外字符(20)(但我認為他不會分配空間),然后它再次通過字符串,但這次相反,將每個不是空格的字符放在新字符串的后面,如果它遇到空格,則將%20放在那里,但它會這樣做相反。

暫無
暫無

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

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