1

我是编程初学者,所以如果我以错误的方式解决问题,请放轻松。我这样做是作为一项任务。我的目的是从用户那里获取一个字符串并用另一个符号替换所有字符。下面的代码应该找到所有的 As 并用 *s 替换。我的代码显示完全出乎意料的结果。还有 _deciphered.length() 的目的是什么。

例如:“I Am A bAd boy”应该变成“I *m * b*d boy”

然后我应该为所有大写和小写字母和数字实现它,并用不同的符号替换,反之亦然,以制作一个小的编码解码程序

#include <iostream>
#include <string>
using namespace std;
string cipher (string);
void main ()
{

    string ciphered, deciphered;
    ciphered="String Empty";
    deciphered="String Empty";
    cout<<"Enter a string to \"Encode\" it : ";
    cin>>deciphered;
    ciphered=cipher (deciphered);
    cout<<endl<<endl;
    cout<<deciphered;
}
string cipher (string _deciphered)
{
    string _ciphered=(_deciphered.replace(_deciphered.find("A"), _deciphered.length(), "*"));
    return _ciphered;
}
4

3 回答 3

4

由于您似乎已经在使用标准库,

#include <algorithm> // for std::replace

std::replace(_deciphered.begin(), _deciphered.end(), 'A', '*');

如果您需要手动执行此操作,请记住 anstd::string看起来像 的容器char,因此您可以遍历其内容,检查每个元素是否为'A',如果是,请将其设置为'*'

工作示例:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string s = "FooBarro";
  std::cout << s << std::endl;
  std::replace(s.begin(), s.end(), 'o', '*');
  std::cout << s << std::endl;
}

输出:

富巴罗

F**巴尔*

于 2013-10-23T15:48:29.607 回答
1

您可以使用std::replace

std::replace(deciphered.begin(), deciphered.end(), 'A', '*');

此外,std::replace_if如果要替换与特定条件匹配的多个值,也可以使用。

std::replace_if(deciphered.begin(), deciphered.end(), myPredicate, '*');

如果字符与要替换的条件匹配,则myPredicate返回。true因此,例如,如果要同时替换aand AmyPredicate则应trueaandA和 false 为其他字符返回。

于 2013-10-23T15:49:13.430 回答
0

我个人会使用常规表达式替换用 * 替换“A 或 a”

看看这个答案的一些指针:有条件地替换字符串中的正则表达式匹配

于 2013-10-23T15:52:44.813 回答