1. 程式人生 > >字串相關操作————字串操作需要注意的一些東西

字串相關操作————字串操作需要注意的一些東西

例題:

#include<stdlib.h>
#include<stdio.h>

int main(){
	char str1[]="hello world";
	char str2[]="hello world";

	char *str3="hello world";
	char *str4="hello world";

	if(str1==str2)
		printf("str1 is same as str2\n");
	else
		printf("str1 not same as str2\n");

	if(str3==str4)
		printf("str3 is same as str4\n");
	else
		printf("str3 not same as str4\n");
	system("pause");
	return 0;
}
輸出的結果應該是:

str1 is not same as str2

str3 is same as str4

解釋:

str1和str2是兩個字串組,我們會為他們分配兩個長度為12個位元組的空間,並把"hello world"的內容分別複製到陣列中去。這是兩個初始地址不同的陣列,因此str1和str2的值也不同,所以輸出的第一行是str1 is not same as str2。

str3和str4是兩個指標,我們無須為他們分配記憶體以儲存字串的內容,而只需要把它們指向“hello world”在記憶體中的地址即可。由於“hello world”是常量字串,它在記憶體中只有一個拷貝,因此str3和str4指向的是同一地址。所以比較str3和str4的值得到的結果是相同的,輸出的第二行是“str3 is same as str4”

替換空格操作:

題目:請實現一個函式,把字串中的每個空格替換成“%20”。例如輸入“we are happy”,則輸出“we%20are%20happy”。

程式碼如下:

void replaceblank(char string[],int length){
	if(string == NULL || length==0){
		return;
	}
	int original_length =0;
	int numofblank=0;
	int i=0;
	//搜尋整體字串的長度和空格的個數
	while(string[i]!='\0'){
		original_length++;
		if(string[i]==' ')
			++numofblank;
		i++;
	}
	//算出轉換之後的字串的長度
	int newlength = original_length + numofblank*2;
	if(newlength > length)
		return;

	int indexoforiginal = original_length;
	int indexofnew =  newlength;
	while(indexoforiginal>=0 && indexofnew > indexoforiginal){
		if(string[indexoforiginal]==' '){
			string[indexofnew--] = '0';
			string[indexofnew--] = '2';
			string[indexofnew--] = '%';
		}else{
			string[indexofnew--] = string[indexoforiginal];
		}
		indexoforiginal--;
	}
}
解析:

從字串的後面開始複製和替換。首先準備兩個指標,P1和P2。P1指向原始字串的末尾,而P2指向替換之後的字串的末尾。接下來向前移動指標P1,逐個把它指向的字元複製到P2指向的位置,知道碰到第一個空格為止。碰到第一個空格之後,把P1向前移動1格,在P2之前插入字串%20.由於%20長度為3,同時也要把P2向前移動3格。