uacs2024

导航

复试C++15真题_程序设计4_查找字符串并替换 ??

复试C++15真题_程序设计4_查找字符串并替换

编写findRepStr函数,功能为在字符串str中寻找目的字符串findStr,并用replaceStr字符串替换,最后输出替换后的字符串str

我不知道可不可以用string,于是我用了字符数组,用暴力匹配寻找字符串。

#include <iostream>
using namespace std;
#include <cstring>

void findRepStr(char str[],const char findStr[],const char replaceStr[]){
    int i = 0,j = 0;//i-size1-findstr  , j-size2-str
    int size2 = strlen(str),size1 = strlen(findStr),size3 = strlen(replaceStr);
    while(i < size1 && j < size2){
        if(str[j]==findStr[i]){
            ++i;++j;
            continue;
        }
        else{
            j = j - i + 1;
            i = 0;
        }
    }
    if(i != size1)  {cout << str << endl;return;}

    int num = j-i;  //num表示目标字符串在str的位置
    char *tStr = new char[size2-size1+size3+1];
int k; for(k = 0;k < num;k++) tStr[k] = str[k]; for(int m = 0;m < size3;m++,k++) tStr[k] = replaceStr[m]; for(int m = num + size1;m < size2;k++,m++) tStr[k] = str[m]; tStr[k] = '\0';
cout
<< tStr << endl; delete []tStr; } int main(){ findRepStr("aababcabcdab","abc","@@@@@@@@"); }

参考答案的方法:

#include <iostream>
#include <string>
using namespace std;
void FindRepStr(char str[],const char findStr[],const char replaceStr[]){
    string s1(str);
    string s2(findStr);
    string s3(replaceStr);
    size_t pos = s1.find(s2);
    while (pos != string::npos) { //npos 是一个常数,表示 size_t的最大值用来表示不存在的位置
        s1.replace(pos,s2.length(),s3); //将从 pos 开始,长度为s2.length()的字符串替换为 s3
        pos = s1.find(s2,pos);
    }
    cout << s1 << endl;
}
int main(){
    char s1[] = "Gao m za Enza za";
    char s2[] = "za";
    char s3[] = "Van";
    FindRepStr(s1, s2, s3);
    return 0;
}

 

posted on 2024-03-21 17:23  ᶜʸᵃⁿ  阅读(7)  评论(0编辑  收藏  举报