/*
The string is: To do or not to do, It is a question!
Enter your want to find a character string: not
Enter you want to replace a character string: and
To do or not to do, It is a question!
To do or and to do, It is a question!
替换的单词必须与原单词长度相同,长度不同的情况实例如下:
The string is: To do or not to do, It is a question!
Enter your want to find a character string: do
Enter you want to replace a character string: kill
To do or not to do, It is a question!
Tokil or not tokil, It is a question!
*/
#include <stdio.h>
#include <string.h>
char * Find(char *, const char *, const char *, int);
void Replace(char *, const char *, int);
int main(void) {
int lenB = 4, lenC = 4, ch, i;
char a[] = "To do or not to do, It is a question!";
char b[lenB];
char c[lenC];
printf("Enter your want to find a character string: ");
for (i = 0; (ch = getchar()) != '\n'; i++){
if (i < lenB)
b[i] = ch;
else
printf("Not enough space, The character stirng is too long !");
}
printf("Enter you want to replace a character string: ");
for (i = 0; (ch = getchar()) != '\n'; i++){
if (i < lenC)
c[i] = ch;
else
printf("Not enough space, The character stirng is too long !");
}
printf("%s\n", a);
Find(a, b, c, lenC - 1);
printf("%s", a);
return 0;
}
char * Find(char * a, const char * b, const char * c, int cLen){
char * pApear = NULL;
const char * pB;
while (*a++){
for (pB = b; *pB; pB++){
if (*a != *pB)
break;
else
a++;
}
if (*pB == '\0'){
pApear = a;
Replace(a-1, c, cLen-1);
}
}
return pApear;
}
void Replace(char * a, const char * c, int cLen){
while (cLen > -1)
*a-- = c[cLen--];
return;
}
查找字符串中的单词并替换
最新推荐文章于 2020-07-23 17:22:11 发布