1. 程式人生 > 其它 >C語言學習之字串:替換空格

C語言學習之字串:替換空格

技術標籤:C++字串c++資料結構

替換空格

函式描述

函式:

char *replace_blank(char *source)

功能:
將字串中的空格替換為"%20"的字串。

思路:

while(字串未到末尾\0)
{
	if(此處字元為空格)
	{
		子函式:刪除空格符;
		子函式:字串向後挪動可以插入陣列的空間;
		子函式:將目標陣列插入到字元陣列的前幾位;
		字串向後移位跳過插入的陣列;
	}
	如果沒有空格符,則再向後移位判斷;
}

難點:
涉及到的子函式較多,由於陣列插入操作本身就是需要移位再插入,需要基本的子函式進行操作。
涉及continue

的使用。

缺點:
暫時還沒有。
時空複雜度為O(n)

函式程式碼

/* 替換空格 */
/** 刪除空格符 **/
void delete_array(char *source, int offset)
{
  int i;
  int len = strlen(source);

  for (i = 0; i < len && source[i] != '\0'; i++)
  {
    source[i] = source[i + offset];
  }

}
/** 向後挪動字元陣列 **/
void move_array(char *source, int offset)
{ int i; int len = strlen(source); for (i = len + offset; i >= 0; i--) { source[i] = source[i - offset]; } } /* 將字串賦值到字元陣列的前幾位 */ void string_set(char *source,char *buf, int offset) { int i; for (i = 0; i < offset; i++) { source[i] = buf[i]; } } char *replace_blank(char
*source) { char *temp = source; int len = strlen(source);//不計算空字元,如何判斷是否為最後一位 char *replace_buf = (char *)"%20"; unsigned int replace_len = strlen(replace_buf); int i; for(i = 0; i < len; i++) { if (*source == ' ') { delete_array(source, 1);//刪除空格 move_array(source, replace_len);//向後挪動,以便插入陣列 string_set(source, replace_buf, replace_len);//將陣列賦值到前幾位 source += replace_len; continue; } source++; } return temp; }``` ```cpp #define MAXLINE 100000 static char source[MAXLINE] = "I am a student."; void test_replace_blank() { replace_blank(source); cout << "The replace result:" << source << endl; } int main() { test_replace_blank(); system("pause"); return 0; }

測試結果

在這裡插入圖片描述