在一個字符串中刪除指定的字符 & 刪除字符串中所有出現在另一個字符數組中的字符

#include <stdio.h>
#include <assert.h>
#include <string.h>

/*在一個字符串中刪除指定的字符,這種算法只用到原來的存儲空間,不用另闢空間*/
char* DeleteChar(char* str,char ch)
{
	assert(str != NULL);
	int iDes = 0;
	int iSrc = 0;
	while(str[iSrc] != '\0')
	{
		if(ch != str[iSrc])
		{
			str[iDes] = str[iSrc];
			iDes++;
			iSrc++;
		}
		else
			iSrc++;
	}
	str[iDes] = '\0';
	return str;
}


/*刪除str字符串中的在ch數組中存在的字符,n爲ch[]數組的長度*/
char* DeleteChar(char* str,char ch[],int n)
{
	assert(str != NULL);
	
	char tmp[256] = {0};
	int i=0;
	/*因爲只有256個字符,故在操作時用tmp[256]數組來存放要刪除的字符,*/
	for(i;i<n;i++)
	{
		//要刪除的字符在tmp數組中對應置1
		tmp[ch[i]] = 1;
	}

	int iDes = 0;
	int iSrc = 0;
	while(str[iSrc] != '\0')
	{
		//不是要刪除的字符,則進行操作。
		if(!tmp[str[iSrc]])
		{
			str[iDes] = str[iSrc];
			iDes++;
			iSrc++;
		}
		else
			iSrc++;
	}
	//記得將最後修改過後的字符串末尾添加結束符
	str[iDes] = '\0';
	return str;
}

/*上面算法的關鍵之一在於設置了標記讀寫位置的變量,這樣不用增加額外的內存空間和重複的拷貝,直接在給定的空間實現了算法。
關鍵之二在於用一個數組來記錄待刪除的字符組,有利於對待刪除的字符進行查找和判定。*/


void main()
{
	//注意這裏應該將str定義爲數組,如這種形式不行:	char* str = "Hello world!"; 會發生錯誤,因爲這種寫法,str的數據是存儲在常量存儲區的。
	char str[] = "Hello world!";
	//char ch = 'o';
//	char ch[] ={'w','l','o'};
	char ch[] = "wlo";
	printf("%s\n",str);
	printf("%d\n",strlen(ch));
	DeleteChar(str,ch,strlen(ch));
	printf("%s\n",str);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章