C/C++字符串匹配和替换

来源:互联网 发布:冒险岛v矩阵 编辑:程序博客网 时间:2024/05/23 19:17

题目:输入三个字符串a,b和c,将a中b的第一次出现替换为c。

代码:

#include <iostream.h>
#include <string.h>

/*字符串替换,第一个参数为原串,第二个参数为要匹配的子串
第三个参数为要替换的第一个子串中包含第二个子串的部分*/
char *strReplace(char *str1,char *str2,char *str3);

 

void main()
{
       char str1[255]={'/0'},str2[255]={'/0'},str3[255]={'/0'};
       cin>>str1;
       cin>>str2;
       cin>>str3;
       strcpy(str3,strReplace(str1,str2,str3));
       cout<<str3<<endl;

}

/*字符串查找匹配函数,查找第二个字符串在第一个字符串中的位置*/
//涛涛认为自己写的这个字符串匹配函数还是很有使用价值的,正在学习

int strSearch(char *str1,char *str2)
{
       int at,flag=1;
       if (strlen(str2) > strlen(str1))
       {
           at = -1;
       }
       else if (!strcmp(str1,str2))
       {
           at = 0;
       }
       else
       {
            unsigned i=0,j=0;
            for (i=0;i < strlen(str1)&&flag;)
           {
                  for (j=0;j < strlen(str2)&&flag;)
                 {
                       if (str1[i]!=str2[j])
                       {
                              i++;
                              j=0;
                       }
                       else if (str1[i]==str2[j])
                       {
                              i++;
                              j++;
                       }
                       if (j==strlen(str2))
                       {
                             flag = 0;
                       }
                 }
            }
            at = i-j;
       }
       return at;
}

/*字符串替换,返回替换后的字符串*/
char *strReplace(char *str1,char *str2,char *str3)
{
       static char str[255]={'/0'};
       int len1,len2,len3,pos;
       len1=strlen(str1);
       len2=strlen(str2);
       len3=strlen(str3);
       pos = strSearch(str1,str2);
       if (pos>=0)
       {
             for (int i=0;i<pos;i++)
             {
                  str[i]=str1[i];
             }
             for (i=0;i<len3;i++)
             {
                  str[pos+i]=str3[i];
             }
              int j=pos+len3;
              for (i=pos+len2;i<len1;i++)
              {
                   str[j]=str1[i];
                   j++;
              }
        }
        else strcpy(str,str1);
        return str; 
}

//涛涛正在学习中……

原创粉丝点击