21xrx.com
2025-04-11 00:33:36 Friday
文章检索 我的文章 写文章
C++ 如何判断字符串是否为空格?
2023-06-30 16:40:35 深夜i     89     0
C++ 判断 字符串 空格

在C++中,判断字符串是否为空格需要对每个字符进行检查,在所有的字符都是空格的情况下字符串被视为只包含空格。

下面是一个简单的C++程序,用于检查字符串是否只包含空格:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
bool isOnlyWhiteSpace(std::string inputString) {
  std::istringstream iss(inputString);
  std::vector<std::string> results(std::istream_iterator<std::string>{iss},
                   std::istream_iterator<std::string>());
  for (auto str : results) {
    for (auto character : str) {
      if (character != ' ')
        return false;
      
    }
  }
  return true;
}
int main() {
  std::string input;
  std::getline(std::cin, input);
  if (isOnlyWhiteSpace(input))
    std::cout << "Only white space found in input string." << std::endl;
   else
    std::cout << "Non-white space characters found in input string." << std::endl;
  
  return 0;
}

在这个程序中,我们首先定义了一个 bool型函数isOnlyWhiteSpace,用以检查输入的字符串是否只包含空格,返回 true 或 false。

这个函数首先将输入字符串插入到std::istringstream中,并使用一个std::vector来存储每个单词。然后,使用双层for循环对字符串进行检查以确定它是否只包含空格。

最后,在main函数中,使用std::getline从输入流中读取字符串,并将其作为参数传递给isOnlyWhiteSpace函数进行检查。如果检查结果为 true,则打印输出语句,“Only white space found in input string。”否则,打印输出语句“Non-white space characters found in input string.”。

总的来说,判断字符串是否只包含空格,需要对字符串中的每个字符进行逐一检查。这个简单的程序演示了如何实现这一功能。

  
  

评论区

请求出错了