C++ 在不使用 C 字符串库函数的情况下替换数组中的字符
C++ Replacing a character in an array without the use of C-String Library Functions
我得到了一组问题,基本上要求我在不使用它们的情况下重新创建某些库函数(如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
相同的内容,因此不会更新任何内容。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在不更改现有函数语法的情况下将普通指针替换为共享指针
- 如何在不重写整个视频文件的情况下仅替换流中的一个数据框架?(ffmpeg)
- 在没有其他变量的情况下替换值的程序
- 在这种情况下,有没有办法用单个解决方案替换两个仅在类型上不同的相似函数?
- C++ 在不使用 C 字符串库函数的情况下替换数组中的字符
- 在不使用退格键的情况下替换 Linux 终端中的文本
- 如何在没有波浪号替换的情况下获取真实文件名
- 如何使用c++uniform_int_distribution在不替换的情况下进行采样
- 如何在不重新建立堆不变量的情况下有效地替换堆的顶部元素
- 如何在复杂情况下执行宏替换
- 如何在不删除屏幕图片的情况下,将invalide替换为转到OnDraw的函数
- 可视化 如何在没有正则表达式的情况下实现C++高效的全词字符串替换