为什么string :: find的行为不同?

时间:2019-07-09 11:28:10

标签: c++ string if-statement find

bool check_tape(char* tape) {
    int test8; 
    cout << example <<" "<<example.size()<<" "<<alpha_sym<<" "<< endl;
    cin >> test8; //To pause the program, temporary 
    int err = 0;
    for (int i = 0; i < example.size(); i++) {
        if (alpha_sym.find(example[i]) >= 0 && alpha_sym.find(example[i]) < example.size()) {
            cout << alpha_sym.find(example[i]) << " " << endl;
            err += 0;
        }
        else {
            cout << example[i]<<" "<< i << " не содержится в алфавите" << endl;
            err++;
        }
    }
    if (err) {
        return 1; //Temporary I made here return 1, else program will crash 
        //get_acmd();
    }
    else return 1;
}

在一种情况下,find将按预期返回第一个条目的位置,但在其他情况下,它将返回char本身。
111 + 11-字符串,并且其中的字符正在其他字符串“ 1 + _”中搜索

与1435 + 212和01234567 + _相同

Good case

Strange case

1 个答案:

答案 0 :(得分:1)

正如在对该问题的评论中已经指出的那样,if语句中有一个错字

if (alpha_sym.find(example[i]) >= 0 && alpha_sym.find(example[i]) < example.size())
                                                                    ^^^^^^^^^^^^^^

必须至少有example.size()而不是alpha_sym.size()

但是无论如何情况都太复杂了,方法find通常被调用3次。

此代码段

for (int i = 0; i < example.size(); i++) {
    if (alpha_sym.find(example[i]) >= 0 && alpha_sym.find(example[i]) < example.size()) {
        cout << alpha_sym.find(example[i]) << " " << endl;
        err += 0;
    }
    else {
        cout << example[i]<<" "<< i << " не содержится в алфавите" << endl;
        err++;
    }
}

可以通过以下方式重写

for ( std::string::size_type i = 0; i < example.size(); i++ )
{
    auto n = alpha_sym.find( example[i] );

    if ( n != std::string::npos )
    {
        std::cout << n << " " << std::endl;
    }
    else
    {
        std::cout << example[i] << " " << i << " не содержится в алфавите" << std::endl;
        ++err;        
    }
}

如果您的编译器支持C ++ 17,那么您甚至可以编写以下方式

for ( std::string::size_type i = 0; i < example.size(); i++ )
{
    if ( auto n = alpha_sym.find( example[i] ); n != std::string::npos )
    {
        std::cout << n << " " << std::endl;
    }
    else
    {
        std::cout << example[i] << " " << i << " не содержится в алфавите" << std::endl;
        ++err;        
    }
}

请注意,(我认为是简化的)函数的未使用参数tape应该声明为

bool check_tape( const char *tape )

前提是该功能未更改。在这种情况下,您将能够将字符串文字作为函数参数传递。

这是一个演示程序

#include <iostream>
#include <string>

int main()
{
    std::string example( "1435+212" );
    std::string alpha_sym( "01234567+_" );
    unsigned int err = 0;

    for ( std::string::size_type i = 0; i < example.size(); i++ )
    {
        auto n = alpha_sym.find( example[i] );

        if ( n != std::string::npos )
        {
            std::cout << n << " " << std::endl;
        }
        else
        {
            std::cout << example[i] << " " << i << " не содержится в алфавите" << std::endl;
            ++err;        
        }
    }
}

其输出为

1 
4 
3 
5 
8 
2 
1 
2 
相关问题