將一個字符串中的空格替換成「%20」python
C語言:c++
1 /* 2 ----------------------------------- 3 經過函數調用,傳地址來操做字符串 4 1.先計算出替換後的字符串的長度 5 2.從字符串最後一個字符串開始往右移 6 ----------------------------------- 7 */ 8 9 10 # include <stdio.h> 11 # include <string.h> 12 13 void replace(char * arr) 14 { 15 int i, j, len, count; 16 count = 0; 17 len = strlen(arr); 18 19 for (i=0; i<len; i++) 20 { 21 if (arr[i] == ' ') 22 { 23 count++; 24 } 25 } 26 27 i = len; 28 j = 2 * count + len; //每個空格用三個字符替換,因此至關於每一個空格多2個字符; 29 printf("處理前的字符串爲:%s\n", arr); 30 31 while (i!=j && i>=0) 32 { 33 if (arr[i] == ' ') 34 { 35 arr[j--] = '0'; 36 arr[j--] = '2'; 37 arr[j--] = '%'; 38 i--; 39 } 40 else 41 { 42 arr[j] = arr[i]; //第一次替換的是字符串的結束符'\0' 43 j--; 44 i--; 45 } 46 } 47 printf("處理後的字符串爲:%s\n", arr); 48 } 49 50 int main(void) 51 { 52 char str[] = "We Are Happy."; 53 replace(str); 54 55 return 0; 56 } 57 58 /* 59 在Vc++6.0中的輸出結果爲: 60 ----------------------------------- 61 處理前的字符串爲:We Are Happy. 62 處理後的字符串爲:We%20Are%20Happy. 63 Press any key to continue 64 ----------------------------------- 65 */
另外,在C中,計算數組中元素個數用sizeof數組
int a[] = {1, 3, 5, 6, 9};app
int m = sizeof(a)/sizeof(int);函數
Python:spa
若是須要修改字符串,則先轉換爲列表,最後再經過join轉爲字符串code
方法一:blog
s = 'hello my baby' def rep(s): li = [] for i in s: li.append(i) for i in range(len(li)): if li[i] == ' ': li[i] = '%20' return ''.join(li) s = rep(s) print(s)
方法二:字符串
s = 'hello my baby' def rep(s): li = [] for i in s: li.append(i) for i in li: if i==' ': li[li.index(i)]='%20' return ''.join(li) s = rep(s) print(s)