如何将字符串与多个字符进行比较c ++ [英] how to compare string to multiple char c++

查看:53
本文介绍了如何将字符串与多个字符进行比较c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找字符串中是否包含单词

I'm trying to find out whether a string has words in it

if( mystring[i] == 'a' | 'b' | 'c' | 'd' | 'e' |)
   // do stuff but it always does stuff no matter that mystring[i] is. 

即使mystring [i] =一个空格或一个句点,

总是求值为true我尝试使用strcmp,但无法正常工作.我希望它评估为真实仅当它=一个字母时.

is always evaluating to true even if mystring[i] = a space or a period I tried to use strcmp but I couldn't get that working right. I want it to evaluate true only if it = a letter.

推荐答案

您不能像这样比较多个值.改用 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
}

这篇关于如何将字符串与多个字符进行比较c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆