字符替换
实例说明
编制一个字符替换函数 rep(char *s,char *s1,char *s2),实现将已知字符串 s 中所有属于字符串
s1 中的字符都用字符串 s2 中的对应字符代替。
实例解析
例如设字符串 s,s1,s2 分别为如下所示。
char s[ ]"= "ABCABC",s1[ ]= "AC",s2[ ]= "xy";
则调用函数 rep(s,s1,s2)将使字符串 s 的内容变为"xByxBy"。
为了实现上述要求,可用一个循环顺序访问字符串 s 中的字符,并检查该字符是否在字符串
s1 中出现,若不在字符串 s1 中出现,则略过该字符;若在字符串 s1 中出现,则用字符串 s2 中的
对应字符代替 s 中的字符。
程序代码
#include <stdio.h>
// system("cls");/* 清屏 */
void clrscr(){
system("cls");/* 清屏 */
}
#define MAX 50
/* 函数 rep 实现对 s 中出现的 s1 中的字符替换为 s2 中相应的字符 */
void rep(char *s,char *s1,char *s2)
{
char *p;
for(;*s;s++)/*顺序访问字符串 s 中的每个字符*/
{
for(p=s1;*p&&*p!=*s;p++);/*检查当前字符是否在字符串 s1 中出现*/
if(*p)*s=*(p-s1+s2);/*当前字符在字符串 s1 中出现,用字符串 s2 中的对应字符代替 s 中的字符*/
}
}
/*示意程序*/
int main()
{
char s[MAX];/*="ABCABC";*/
char s1[MAX],s2[MAX];
clrscr();
puts("Please input the string for s:");
scanf("%s",s);
puts("Please input the string for s1:");
scanf("%s",s1);
puts("Please input the string for s2:");
scanf("%s",s2);
rep(s,s1,s2);
puts("The string of s after displace is:");
printf("%s\n",s);
puts("\n Press any key to quit...");
getch();
return 0;
}
程序运行结果
归纳注释
查找替换是许多文字处理软件,比如 word 必备的基本功能,本例程序实现了较为复杂的替
换功能,其基本原理是相同的。