查找字符串中的单词并替换

/*
 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值