我正在尝试编写一个文字游戏,在文字游戏中,我需要能够知道我可以使用哪些字母。我有一个包含可用字母的字符串,开头是“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/