字符串操作——查找替换

题目描述:在字符串s中查找指定字符串m,并将其替换为字符串t,忽略大小写。

思考:实质是对数组的相关操作。注意:在进行一次替换后元字符串的长度发生改变;有些编译器中不认为-1为false,需在if判断中明确采用==-1形式;

C语言实现:

#include <stdio.h>
#include <stdlib.h>
int myisalpha(const char a) //判读是否为字母
{
    if((a>='a' && a<='z')|| (a>='A' && a<='Z'))
        return 1;
    else
        return -1;
}
int comp(const char a,const char b) //比较函数
{
    if(myisalpha(a) && myisalpha(b)){
        if(a==b || a-'a'==b-'A' || a-'A'==b-'a')
            return 1;
    }else{
        if (a==b)
            return 1;
    }
    return -1;
}
int mystrlen(const char *s)
{
    int r=0;
    while(*s!='\0')
    {
        r++;
        s++;
    }
    return r;
}
int main()
{
    char s[300];
    char t[20];
    char m[20];
    int sl,ml,tl,i,j;
    gets(s);
    gets(m);
    gets(t);
    sl=mystrlen(s);
    ml=mystrlen(m);
    tl=mystrlen(t);
    for (i=0; i<sl; i++)
    {
        if(comp(m[0],s[i])==1) //采用朴素字符串匹配
        {
            for (j=1; j<ml; j++)
            {
                if (comp(m[j],s[i+j])==-1)
                    break;
            }
            if(j==ml )
            {
                if(tl>=ml) //替换串长度大于等于被替换串长度
                {
                    for(j=sl; j>=i+ml; j--) //注意从sl位而不是sl-1位开始后移,因为串s要以'\0'结尾
                    {
                        s[j+tl-ml]=s[j];  //将s串向后移动tl-ml位
                    }
                    for(j=i; j<i+tl; j++) //将字符串t复制过来
                    {
                        s[j]=t[j-i];
                    }
                }
                else //替换串长度小于被替换串长度
                {
                    for(j=i+tl; j<=sl; j++)
                    {
                        s[j+tl-ml]=s[j];
                    }
                    for(j=i; j<i+tl; j++)
                    {
                        s[j]=t[j-i];
                    }
                }
                sl+=tl-ml; //s串长度发生变化
                // i=i+tl-1; 考虑替换后又有可能生成满足替换条件的,所以i不移动
            }
        }
    }
    puts(s);
    return 0;
}

 

posted @ 2015-09-11 19:14  vvi3  阅读(232)  评论(0)    收藏  举报