我有一个文本文件需要读取。我想知道其中是否有一行包含[
,所以我尝试了以下代码:
if(array[i] == "[")
但是这样做不起作用。
我如何检查一个字符串是否包含特定字符?
请查看文档string::find
std::string s = "hell[o";
if (s.find('[') != std::string::npos)
; // found
else
; // not found
npos
是在未找到这样的子字符串时返回的值。 - thibsc从C++23开始,您可以使用std::string::contains
#include <string>
const auto test = std::string("test");
if (test.contains('s'))
{
// found!
}
我是这样做的。
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
}
在字符串中,我们可以使用 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
}
found
代替 firstOccurrence
,用 s
代替 str
,find()
仍然会返回 4 而不是 3。在发布答案前,请至少运行您的代码并确保其正确性,谢谢! - SebastianWilkestring 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
'['
将是一个字符字面值,"["
则是一个 C 字符串。 - Colinarray
? - Jabberwockychar *
,char []
,std::string
,vector<char>
,这些容器都属于这个问题的范畴。@Jabberwocky - Meraj al Maksudstring
和char
没有什么用。没有人会搜索char
。谢谢。 - Lightness Races in Orbitstdstring
更多。 - Meraj al Maksud