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

70

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

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

但是这样做不起作用。

我如何检查一个字符串是否包含特定字符?


6
'[' 将是一个字符字面值,"[" 则是一个 C 字符串。 - Colin
1
什么是 array - Jabberwocky
char *char []std::stringvector<char>,这些容器都属于这个问题的范畴。@Jabberwocky - Meraj al Maksud
1
嗨@Meraj。那些标签本来就很好。添加stringchar没有什么用。没有人会搜索char。谢谢。 - Lightness Races in Orbit
讽刺的是,这两个标签的关注者和问题数量都比 stdstring 更多。 - Meraj al Maksud
5个回答

124

请查看文档string::find

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

1
什么是npos?它是您正在尝试将字符与之匹配的字符串的位置吗? - Adan Vivero
6
如果您阅读文档中“返回值”部分,npos是在未找到这样的子字符串时返回的值。 - thibsc

31

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

#include <string>

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

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

9

我是这样做的。

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
}

你能解释一下它是如何工作的吗? - THUNDER 07
@THUNDER07 文档会有帮助:https://en.cppreference.com/w/cpp/string/basic_string/find - Gourav

3

在字符串中,我们可以使用 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
}

1
这段代码无法编译!即使你用 found 代替 firstOccurrence,用 s 代替 strfind() 仍然会返回 4 而不是 3。在发布答案前,请至少运行您的代码并确保其正确性,谢谢! - SebastianWilke
1
@SebastianWilke 感谢您的更新。我已经修改了我的错误。以后在发布之前我会检查我的代码,不会再犯同样的错误了! - Akash Srinivasan

0
使用find()方法,但记住find()会返回位置!
string str;
char letter, entered_char;

cout<<"Enter  a string: ";
cin>>str;

cout<<"Enter character to be found: ";
cin>>entered_char;

//remember: find() gives the position of char
letter = str.find(entered_char);
//'letter' variable contains the position of entered_char

//if entered character is not equal to str[position found] 
if(entered_char != str[letter]){
    cout<<"Not found!";
} else {
    cout<<"Found";
}

为什么使用char作为字母索引的类型?通常情况下,size_t用于大小和索引。特别是在这里,这将避免将索引缩小为char,如果返回的索引不能表示在char范围内,则会导致错误的值。 - YurkoFlisk
即使您使用了“size_t”,如果未找到字符,则代码将引发未定义的行为,因为“string::find”返回“string::npos”,您将在“if”语句中使用它来索引字符串,使用“string::operator[]”,仅当其索引位于0和字符串长度之间时才定义行为(有关详细信息,请参见文档)。您应该像接受的答案一样只检查索引是否为“npos”。 - YurkoFlisk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接