How to check if a string contains a char?

跟風遠走 提交于 2020-05-08 06:09:28

问题


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?


回答1:


Look at the documentation string::find

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



回答2:


If the array is char* array or char array[], you can find a char through a while loop:

while(i < nSize)
    if (array[i] == '[')

Note: '[' is the correct char literal, but "[" is a string literal.




回答3:


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://stackoverflow.com/questions/43629363/how-to-check-if-a-string-contains-a-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!