简体   繁体   中英

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

I'm trying to code a word game, and in the word game, I need to be able to know what letters I have available to me. I have a string with the available letters, which at the start, would be "abcdefghijklmnopqrstuvwxyzaeiou", the entire alphabet with an extra set of vowels. I need to be able to search the string for a certain character (I might want to use the letter 'c'), and then assuming the character is in the string, remove that character from the string. I'm not entirely sure how to do this, but I'm writing in some pseudocode.

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."
    }

I think I can use string::find to find my character, but I don't know how I'd be able to remove the letter from the string. If there's a better way to go about this, please let me know.

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

Just use std::remove , and the 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));

This is a C++03 version, in case you're stuck with a pre-C++11 compiler:

#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());

In your stead, I would be using a different approach:

std::map<char, size_t> alphabet = init_alphabet("abc....");

With:

#include <map>

std::map<char, int> init_alphabet(std::string const& pool) {
    std::map<char, int> result;
    for (char c: pool) { result[c] += 1; }
    return result;
}

Then, instead of shuffling characters around like crazy, you just check whether the character is in the map:

if (alphabet[input] > 0) {
    alphabet[input] -= 1;
} else {
    std::cerr << "The letter '" << input << "' is not available to you.\n";
}

This way, map does all the heavy-lifting for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM