21xrx.com
2024-09-20 00:09:15 Friday
登录
文章检索 我的文章 写文章
C++中判断空格的方法
2023-06-29 19:29:36 深夜i     --     --
C++ 判断 空格 方法

在C++中,判断字符串中是否含有空格有很多种方法。下面介绍两种常见的方法。

方法一:使用标准库函数find或find_first_of

在C++的标准库中,有两个函数可以用来在字符串中查找特定字符或一组字符。这两个函数分别是find和find_first_of。可以使用这两个函数来判断字符串中是否含有空格。

代码如下:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "hello world";

  int found_pos = str.find(" ");

  if (found_pos != string::npos)

    cout << "The string contains a whitespace" << endl;

   else

    cout << "The string does not contain a whitespace" << endl;

  

  return 0;

}

方法二:使用循环遍历字符串每个字符

另外一种方法是通过循环逐个遍历字符串中的字符,判断每个字符是否为空格。

代码如下:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "hello world";

  bool contains_whitespace = false;

  for (int i = 0; i < str.length(); ++i) {

    if (str[i] == ' ')

      contains_whitespace = true;

      break;

    

  }

  if (contains_whitespace)

    cout << "The string contains a whitespace" << endl;

   else

    cout << "The string does not contain a whitespace" << endl;

  

  return 0;

}

综上所述,以上两种方法都可以用来判断字符串中是否含有空格,使用哪种方法取决于实际情况和个人喜好。

  
  

评论区

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