【问题标题】:Replacing text in a string with hyphens用连字符替换字符串中的文本
【发布时间】:2015-05-19 01:46:59
【问题描述】:

我正在尝试编写一个模拟刽子手游戏的程序。

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

using namespace std;

int main(){
     clearScreen();
     cout << "Enter a  word or phrase: ";
     string phrase;
     std::getline(std::cin, phrase);
     cout << endl << "Your phrase: " << phrase << endl;
     cout << endl;
}

目前我可以获取输入字符串并保留空格,但我想创建另一个字符串,其中所有字母都替换为连字符并保留空格。我已经尝试查找它,但无法找到它。

【问题讨论】:

标签: c++ string getline


【解决方案1】:

您可以使用此函数返回短语字符串的连字符:

std::string replacetohyphen(std::string phrase){
    for(int i=0;i<(int)phrase.length();i++){
    phrase[i]='-';}
    return phrase;}

用法:new_phrase=replacetohyphen(phrase);

如果您也想在这个新的连字符字符串中保留空格,那么for 循环内的一个简单 if 条件就可以解决问题:

std::string replacetohyphen(std::string phrase){
    for(int i=0;i<(int)phrase.length();i++){
    if(phrase[i]!=' ')phrase[i]='-';}
    return phrase;}

【讨论】:

  • 这不会保留空格 - 尽管 OP 没有指定是否需要这样做。
【解决方案2】:

这是使用algorithmreplace_if的示例

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

int main()
{
    using namespace std;

    string input{"This is a test"};
    string censored{input};
    replace_if(censored.begin(), censored.end(), ::isalpha, '-');
    cout << censored << std::endl;
}

输出:

---- -- - ----

上面对replace_if 的调用遍历了一个容器(在本例中为一串字符),并用破折号替换了字母字符,保留了完整的空格。

Live example

【讨论】:

  • 非常感谢,这真的很好用!现在我只需要弄清楚如何用猜测的字母替换破折号。
【解决方案3】:

这是一个手动完成的示例。我保留了您的原始字符串,以便您可以在他们猜到它们时开始替换字母。我发现一开始就自己做事而不是使用算法来了解幕后发生的事情是件好事。

    #include <iostream>
    #include <string>

    using namespace std;

    int main()

    {
         cout << "Enter a  word or phrase: ";

         string originalPhrase;

         std::getline(std::cin, originalPhrase);

         // Copy the original string
         string newPhrase(originalPhrase);
         int phraseSize = originalPhrase.size();
         for(int i = 0; i < phraseSize; ++i)
         {
            // Replace each character of the string with _
            newPhrase[i] = '_';
         }

         cout << endl << "Your phrase: " << originalPhrase << endl;
         cout << endl << "Your new phrase: " << newPhrase << endl;

         cout << endl;
    }

【讨论】:

  • std::string 也有一个接受 size_t 和字符的填充构造函数。这将为您提供与 for 循环相同的结果:string newPhrase(originalPhrase.length(), '_');
猜你喜欢
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
相关资源
最近更新 更多