21xrx.com
2024-09-19 10:12:11 Thursday
登录
文章检索 我的文章 写文章
C++如何判断字符串是否为空格?
2023-07-07 11:29:20 深夜i     --     --
C++ 判断 字符串 空格

在C++中,判断一个字符串是否为空格的方法是使用isspace函数。这个函数可以判断一个字符是不是空格,如果字符是空格,则该函数返回一个非零的值,否则返回0。

如果要判断一个字符串是否全部都是空格,可以使用循环遍历字符串中每个字符,然后调用isspace函数判断字符是否为空格。

下面是一个示例代码:


#include <iostream>

#include <string>

using namespace std;

bool isAllSpace(string str) {

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

    if(!isspace(str[i]))

      return false;

    

  }

  return true;

}

int main() {

  string str1 = "  "; // 全部是空格

  string str2 = " abc "; // 包含空格和其他字符

  string str3 = "abc"; // 全部是其他字符

  cout << "Str1 is all space: " << boolalpha << isAllSpace(str1) << endl;

  cout << "Str2 is all space: " << boolalpha << isAllSpace(str2) << endl;

  cout << "Str3 is all space: " << boolalpha << isAllSpace(str3) << endl;

  return 0;

}

运行结果为:


Str1 is all space: true

Str2 is all space: false

Str3 is all space: false

可以看到,判断一个字符串是否全部都是空格的方法是遍历字符串中每个字符,使用isspace函数判断字符是否为空格。

  
  

评论区

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