尝试在字符串中索引字符并创建新字符串

Trying index characters in strings and create new strings

本文关键字:字符串 创建 字符 索引      更新时间:2023-10-16

我目前正在制作一个快速的刽子手游戏,我正在努力从单词中获取正确猜测的字母并将它们插入到我在用户玩游戏时向用户展示的字符串中。这是我到目前为止的代码:

std::string word_to_guess = "ataamataesaa";
    std::string word_to_fill(word_to_guess.length(), '-');
    char user_guess = 'a';
    for (auto &character : word_to_guess) {
        if (character == user_guess) {
            std::size_t index = word_to_guess.find(&character); 
            word_to_fill[index] = user_guess;
        }
    }
    std::cout << word_to_fill;

这几乎有效,但是它忽略了字符串的最后两个 As 来猜测我无法理解的内容。

"Find" 将仅返回第一次出现。

不要循环访问字符,而是同时迭代word_to_guess和word_to_fill的索引。

for (int i = 0 ; i < word_to_fill.length ; ++i) {
    if (word_to_guess[i] == user_guess) {
        word_to_fill[i] = user_guess;
    }
}