c++ - 如何在字符串中搜索字符,并删除该字符

标签 c++ c++11

我正在尝试编写一个文字游戏,在文字游戏中,我需要能够知道我可以使用哪些字母。我有一个包含可用字母的字符串,开头是“abcdefghijklmnopqrstuvwxyzaeiou”,整个字母表带有一组额外的元音。我需要能够在字符串中搜索某个字符(我可能想使用字母“c”),然后假设该字符在字符串中,从字符串中删除该字符。我不完全确定如何执行此操作,但我正在编写一些伪代码。

string alphabet = "abcdefghijklmnopqrstuvwxyzaeiou"
char input;
cout << "Please input a character.";
cin >> input;
if (input is in the string)
    {
    remove the letter from the string
    }
else
    {
    cout << "That letter is not available to you."
    }

我想我可以使用 string::find 来找到我的角色,但我不知道如何从字符串中删除字母。如果有更好的方法来解决这个问题,请告诉我。

最佳答案

How to search a string for a character, and remove said character

只需使用 std::remove , 和 erase-remove idiom :

#include <string>
#include <algorithm>
#include <iterator>

....

std::string s = .....; // your string
char c = ....;         // char to be removed
s.erase(std::remove(std::begin(s), std::end(s), c), std::end(s));

这是一个 C++03 版本,以防你被 C++11 之前的编译器困住:

#include <string>
#include <algorithm>

....

std::string s = .....; // your string
char c = ....;         // char to be removed
s.erase(std::remove(s.begin(), s.end(), c), s.end());

关于c++ - 如何在字符串中搜索字符,并删除该字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197772/

相关文章:

c++ - 从队列中删除 unique_ptr

C++程序计算最大公约数

c++ - 视频帧上的 cvResize

c++ - 扩展 std::priority_queue 功能

c++ - 显示 vector 的所有元素

c++ - 组织从内存中读取数据的最佳方式(用于调试)c++

c++ - 如何在 VS2010 中痛饮?

c++ - 计算 2 D3DXVECTOR3 与距离无关的 vector

c++ - 重构为枚举以枚举类阴影命名空间

c++ - 使用 push_back 函数调用复制构造函数的 vector 内存分配调用