21xrx.com
2024-06-03 04:22:45 Monday
登录
文章检索 我的文章 写文章
C++中如何判断字符是否在字符串中?
2023-07-12 21:54:18 深夜i     --     --
C++ 判断 字符 字符串

在C++中,要判断一个字符是否在字符串中,可以使用string类提供的find()函数来实现。

比如,如果有一个字符串str和一个字符ch,需要判断ch是否在str中,可以使用以下的代码:


string str = "hello world";

char ch = 'o';

size_t pos = str.find(ch);

if (pos != string::npos)

  cout << ch << " is in the string" << endl;

else

  cout << ch << " is not in the string" << endl;

在上面的代码中,string类的find()函数会在字符串str中查找字符ch第一次出现的位置,并返回该位置的下标,如果没有找到,则返回string::npos(一个常量,表示没有找到)。因此,可以通过判断pos是否等于string::npos来判断字符是否在字符串中。

除了单个字符,也可以判断一个子字符串是否在字符串中。例如:


string str = "hello world";

string substr = "world";

size_t pos = str.find(substr);

if (pos != string::npos)

  cout << substr << " is in the string" << endl;

else

  cout << substr << " is not in the string" << endl;

与上面的代码类似,find()函数可以在字符串中查找子字符串第一次出现的位置,并返回该位置的下标。如果没有找到,则返回string::npos。

在判断字符或子字符串是否在字符串中时,还可以指定查找的起始位置和查找的长度。例如:


string str = "hello world";

char ch = 'o';

size_t pos = str.find(ch, 6); // 从下标为6的位置开始查找

if (pos != string::npos)

  cout << ch << " is in the string" << endl;

else

  cout << ch << " is not in the string" << endl;

string substr = "world";

pos = str.find(substr, 6, 3); // 从下标为6的位置开始查找,查找长度为3

if (pos != string::npos)

  cout << substr << " is in the string" << endl;

else

  cout << substr << " is not in the string" << endl;

上述代码中,第二个参数指定从字符串的哪个位置开始查找,第三个参数指定查找的长度。如果不指定第三个参数,则默认查找整个字符串。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复