C++ 如何检查字符串是否包含字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43629363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a string contains a char?
提问by Robert Lewis
I have a text file that I want to read. I want to know if one of the lines contains [
so I tried :
我有一个想要阅读的文本文件。我想知道其中一行是否包含[
所以我试过:
if(array[i] == "[")
But this isn't working.
但这不起作用。
How can I check if a string contains a certain character?
如何检查字符串是否包含某个字符?
回答by thibsc
Look at the documentation string::find
看文档 string::find
std::string s = "hell[o";
if (s.find('[') != std::string::npos)
; // found
else
; // not found
回答by Akash Srinivasan
In strings, we can use find()
to get the first occurrence (position) of the given "string"
在字符串中,我们可以使用find()
获取给定“字符串”的第一次出现(位置)
string s = "dumm[y[";
int found = s.find('[');
cout<<"$ is present at position "<<firstOccurrence; //$ is present at position 3
if (found < str.length()) {
// char found
}
else{
// char not found
}
回答by u7556173
If the array is char* array
or char array[]
, you can find a char
through a while
loop:
如果数组是char* array
or char array[]
,您可以char
通过while
循环找到 a :
while(i < nSize)
if (array[i] == '[')
Note:'['
is the correct char literal, but "["
is a string literal.
注意:'['
是正确的字符文字,但是"["
是字符串文字。
回答by Varsha
To check if a character of a string is equal to a particular character, you need to check in the below manner:
要检查字符串的字符是否等于特定字符,您需要按以下方式检查:
if(array.at(i) == '[') {
}
Check below link for more details: https://www.geeksforgeeks.org/string-at-in-cpp/##targetText=string%20at()%20in%20C%2B%2B,characters%20from%20a%20given%20string.&targetText=Syntax%202%3A,first%20character%20has%20index%200)
查看以下链接了解更多详情:https: //www.geeksforgeeks.org/string-at-in-cpp/##targetText=string%20at()%20in%20C%2B%2B,characters%20from%20a%20given %20string.&targetText=语法%202%3A,first%20character%20has%20index%200)