//使用C語言實現字符串中子字符串的替換
//描述:編寫一個字符串替換函數,如函數名為 StrReplace(char* strSrc, char* strFind, char* strReplace),
//strSrc為原字符串,strFind是待替換的字符串,strReplace為替換字符串。
//舉個直觀的例子吧,如:“ABCDEFGHIJKLMNOPQRSTUVWXYZ”這個字符串,把其中的“RST”替換為“ggg”這個字符串,
//結果就變成了:ABCDEFGHIJKLMNOPQgggUVWXYZ
#include<stdio.h>
#include<string.h>
void StrReplace(char* strSrc, char* strFind, char* strReplace)
{
int i,j,k,m;
int lengthSrc,lengthFind,lengthReplace;
lengthSrc = strlen(strSrc);
lengthFind = strlen(strFind);
lengthReplace = strlen(strReplace);
for(i=0;i<lengthSrc;)
{
j = 0;
if(strSrc[i] == strFind[j])//遍歷原字符串,如果當前字符與strFind[0]相等,開始逐位判斷
{
do
{
i++;j++;
}while((j < lengthFind) && (strSrc[i] == strFind[j]));
//判斷跳出while循環的條件。如果j == lengthFind表示找到了匹配的字符串。且i指向strSrc中匹配字符串strFind的下一個字符。
if(j == lengthFind)
{
//strFind字符串和strReplace字符串的長度相等時
if(lengthFind == lengthReplace)
{
for(k=i-lengthFind,m=0;m<lengthReplace;k++,m++)
{
strSrc[k] = strReplace[m];
}
}
//strFind字符串的長度小於strReplace字符串的長度
if(lengthFind < lengthReplace)
{
//增加空位。
for(k=lengthSrc;k>=i;k--)
{
strSrc[k+lengthReplace-lengthFind] = strSrc[k];
}
//strSrc長度更新。如果不更新,在下一次增加空位時,會有問題。
lengthSrc += lengthReplace-lengthFind;
//開始替換。
for(k=i-lengthFind,m=0;m<lengthReplace;k++,m++)
{
strSrc[k] = strReplace[m];
}
//strSrc的元素和長度變更後,需要將i重新指向已替換部分的下一個字符。
i+= lengthFind-lengthReplace;
}
//strFind字符串的長度大於strReplace字符串的長度
if(lengthFind > lengthReplace)
{
//減小空位。
for(k=i;k<=lengthSrc;k++)
{
strSrc[k-(lengthFind-lengthReplace)] = strSrc[k];
}
//strSrc長度更新。如果不更新,在下一次減小空位時,會有問題。
lengthSrc -= lengthFind-lengthReplace;
//開始替換。
for(k=i-lengthFind,m=0;m<lengthReplace;k++,m++)
{
strSrc[k] = strReplace[m];
}
//strSrc的元素和長度變更後,需要將i重新指向已替換部分的下一個字符。
i-= lengthFind-lengthReplace;
}
}
}
else
{
i++;
}
}
}
int main()
{
char strSrc[255],strFind[255],strReplace[255];
gets(strSrc);
gets(strFind);
gets(strReplace);
StrReplace(strSrc,strFind,strReplace);
puts(strSrc);
return 0;
}
不同的字符串要兩者之間帶有點關聯,不然只能分兩次替換
比如“我的、他的”替換為“她的”這樣可以一次完成
按CTRL+H打開替換對話框,單擊高級,勾選“使用通配符”
在“查找內容”框中輸入?的
在“替換為”框中輸入她的
單擊“全部替換”
#include<stdio.h>
char* exchange(char* first,char* second,int index,int count) //這兒用的方法很好想,沒什麼難度
//傳入的參數1是要被插入的字符串引用,2是要插入的字符串,3是開始位置,包括index
//位,count是替換的字符數
{
char *temp = new char[100];//必須用new或者malloc(好像是這麼寫的)動態分配空間,
//否則函數結束,定義的數組就沒了
for(int i = 0;i<=index && first[i]!='\0';i++)//三個for循環完成需求,比較笨的方法
{
temp[i] = first[i];
}
int j = 0;
for(;second[j]!='\0';j++)
{
temp[index+j] = second[j];
}
for(int m = 0;first[m]!='\0';m++)
{
temp[index+j+m] = first[index+count+m];
}
return temp;//相當於返回數組temp的指針
}
void main()
{
char *a = "afdadfgg";//如果用{'','',''}形式賦值的話,必須將最後一個字符賦值為'\0'
char *b = "lkl";
a = exchange(a,b,2,2);
printf("插入後的字符為%s\n",a);
}
//其實以後你學了C++就會發現其實要實現這樣的操作很簡單的,不過平時多做些這樣的編程也
//很有好處的