C++ 在不使用 C 字符串库函数的情况下替换数组中的字符

C++ Replacing a character in an array without the use of C-String Library Functions

本文关键字:情况下 替换 数组 字符 库函数 字符串 C++      更新时间:2023-10-16

我得到了一组问题,基本上要求我在不使用它们的情况下重新创建某些库函数(如strlen()和strcpy())的实用程序。

然而,其中一个问题让我难倒了。它是一个函数,可将字符串中的字符替换为您选择的任何字符。

例:

斯特 : 马里克斯

·

目标 : X

替换 : O

输出:马里奥奥德赛

这就是我现在所拥有的

#include <iostream>
using namespace std;
int replace(char *s2, char target, char replacementChar);
const int MAX_SIZE = 128;
int main()
{
    char str2[MAX_SIZE], target, replacement;
    int change;
    cout << "Enter your string : " << endl;
    cin.getline(str2, MAX_SIZE);
    cout << "What's your target?" << endl;
    cin >> target;
    cout << "What do you want to replace it with?" << endl;
    cin >> replacement;
    replace(str2, target, replacement);
}
int replace(char *s2, char target, char replacementChar)
{
    int change = 0;
    for(int i=0; s2[i]!=''; i++)
    {
        if(s2[i] == target)
        {
            swap(s2[i], replacementChar);
            change++;
        }
    }
    cout << "There were " << change << " change(s)." << endl;
    cout << s2;
    return change;
}

即使"更改"返回 2,我也得到了"mario xdyssey"的输出。

关于如何进行的任何建议或提示将不胜感激。

更改

        swap(s2[i], replacementChar);

自:

        s2[i] = replacementChar;

swap()交换两个变量的值,因此在第一次替换后,replacementChar包含与target相同的内容,因此不会更新任何内容。

相关文章: