且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串与多个字符进行比较c ++

更新时间:2023-01-29 15:34:10

您不能像这样比较多个值.改用 switch 语句:

You cannot compare multiple values like that. Use a switch statement instead:

switch( mystring[i] )
{
    case 'a':
    case 'b':
    case 'c':
    case 'd':
    case 'e':
    {
        // do something
        break;
    }
    default:
    {
        // do something else
        break;
    }
}

在C/C ++中,如果 case 块没有 break ,则它将在下一个 case 块中继续执行.因此,所有5个值将执行相同的//做某事代码.某些语言不这样做.

In C/C++, if a case block does not have a break then its execution will continue in the next case block. Thus, all 5 values will execute the same // do something code. Some languages do not do that.

另一个选择是,仅因为您的值是连续的,才可以使用它:

Another option, only because your values are consecutive, is to use this:

char ch = mystring[i];
if( (ch >= 'a') && (ch <= 'e') )
{
    // do something
}
else
{
    // do something else
}