【问题标题】:How to check if a string contains a char?如何检查字符串是否包含字符?
【发布时间】:2017-09-23 13:42:39
【问题描述】:

我有一个想要阅读的文本文件。我想知道其中一行是否包含[,所以我尝试了:

if(array[i] == "[")

但这不起作用。

如何检查字符串是否包含某个字符?

【问题讨论】:

  • '[' 是 char 文字,"[" 是 c 字符串。
  • 什么是array
  • char *char []std::stringvector<char>,我认为这些容器中的任何一个都属于这个问题的范畴。 @Jabberwocky
  • 嗨@Meraj。那些标签本来就很好。添加stringchar 没有用。没有人搜索char。谢谢。

标签: c++ stdstring


【解决方案1】:

查看文档string::find

std::string s = "hell[o";
if (s.find('[') != std::string::npos)
    ; // found
else
    ; // not found

【讨论】:

  • 什么是 npos?那是你试图匹配字符的字符串的位置吗?
  • @AdanVivero,如果您阅读了文档的 返回值 部分,npos 是未找到此类子字符串时返回的值。
【解决方案2】:

从 C++23 开始你可以使用std::string::contains

#include <string>

const auto test = std::string("test");

if (test.contains('s'))
{
    // found!
}

【讨论】:

  • 只用了35年!
【解决方案3】:

我是这样做的。

string s = "More+";

if(s.find('+')<s.length()){ //to find +
    //found
} else {
    //not found
}

即使您想找到多个字符,它也可以工作,但它们应该排列在一起。请务必将'' 替换为""

string s = "More++";

if(s.find("++")<s.length()){ //to find ++
    //found
} else {
    //not found
}

【讨论】:

    【解决方案4】:

    在字符串中,我们可以使用find() 来获取给定“字符串”的第一次出现(位置)

    string s = "dumm[y[";
    int found = s.find('[');
    
    cout<<"$ is present at position "<<firstOccurrence;   //$ is present at position 4
    
    if (found < str.length()) {
        // char found
    }
    else{
        // char not found
    }
    

    【讨论】:

    • 这段代码无法编译!即使您将firstOccurrence 替换为found 并将str 替换为sfind() 将返回 4,而不是 3。请至少运行您的代码并确保它是在此处发布答案之前更正,谢谢!
    • @SebastianWilke 感谢您的更新。编辑了我做的错误。在发布之前检查我的代码,并且不会再重复它。!
    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 2013-05-18
    • 2011-03-31
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2012-04-21
    相关资源
    最近更新 更多