替換空格
替換空格
把字元串中的每個空格替換成"%20"
思路:
空格一個字元,替換後變成3個字元,因此字元串變長了,應該從後向前替換。參考答案:
#include <stdio.h>void replaceBlank(char* str,int len){if(str ==NULL || len <=0) return;int originalLen = 0;int numofBlank = 0;int i = 0;while(str[i] != ){ originalLen++; if(str[i] == ) numofBlank++; i++;}int newLen = originalLen + 2*numofBlank;if(newLen > len) return;int indexofOriginal = originalLen;int indexofNew = newLen;while(indexofOriginal >0 && indexofNew > indexofOriginal){ if(str[indexofOriginal] == ) { str[indexofNew--] = 0; str[indexofNew--] = 2; str[indexofNew--] = %; } else str[indexofNew--] = str[indexofOriginal]; indexofOriginal--;}}int main(){char str[100]="abcde fghij lmnop";replaceBlank(str,100);printf("str=%s",str);return 0;}
推薦閱讀: