我如何从字符串中找到字符(变量)?

问题描述 投票:0回答:1
cin >> letter >> position; //This is inside the main(). 

void moveLetter(char letter, int position) {`

    if (upperRowPiecesToPlay.find(letter)) {

        upperRowPiecesToPlay.replace(letter,1 , " ");

            switch(position) {

                case 1:
                    if(p1 == '.' ) {
                    p1 = letter;
                    }

                    break;

所以,这是我的代码。

我想从给定的字符串中找到一个字符(来自用户的输入)。并替换为空白。

但是,显然,这不是我应该使用查找和替换的方式。

请以正确的方式教我...

c++ string character
1个回答
1
投票

您没有正确使用std::string::find()的返回值。

std::string::find()返回指定字符的index,如果找不到,则返回std::string::find()(-1)。它不返回std::string::npos,就像您的代码似乎认为的那样。

评估bool语句时,将非零整数值视为true。这意味着如果在任何索引非0根本找不到处找到if,您的代码将尝试执行upperRowPiecesToPlay.replace()

但是没有letter的重载将std::string::replace()作为输入。如果不是std::string::replace(),则需要给它赋予letter返回的索引。

尝试以下方法:

find()
© www.soinside.com 2019 - 2024. All rights reserved.