加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 用连字符替换字符串中的文本

发布时间:2020-12-16 09:57:00 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个模拟Hangman游戏的程序. #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:
我正在尝试编写一个模拟Hangman游戏的程序.

#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;
}

目前我可以获取输入字符串并保留空格,但我想创建另一个字符串,其中所有字母都用连字符替换,并保留空格.我试过查找它,但无法找到如何做到这一点.

解决方法

以下是使用algorithm的replace_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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读