21xrx.com
2024-06-03 04:22:08 Monday
登录
文章检索 我的文章 写文章
如何在C++中计算字符串开头的空格数?
2023-07-06 10:24:13 深夜i     --     --
C++ 字符串 空格 计算 开头

在C++中,一个空格可以使用空格符或制表符来表示,计算字符串开头的空格数可以通过逐个遍历字符串中的字符,并确定其是否为空格来实现。下面是一个简单的示例:


#include <iostream>

#include <string>

int countLeadingSpaces(const std::string& str) {

  int count = 0;

  for (char ch : str) {

    if (ch == ' ' || ch == '\t') {

      ++count;

    } else

      break;

    

  }

  return count;

}

int main() {

  std::string str = "   Hello World!";

  int count = countLeadingSpaces(str);

  std::cout << "Leading spaces: " << count << std::endl;

  return 0;

}

在上面的示例中,`countLeadingSpaces`函数接收一个`std::string`类型的参数,并返回一个整数类型的值,表示该字符串开头的空格数。该函数逐个遍历字符串中的字符,如果遇到一个空格或制表符,则将计数器`count`加1;否则跳出循环并返回计数器的值。

在`main`函数中,我们定义了一个字符串`str`,该字符串包含了一些空格,我们通过调用`countLeadingSpaces`函数并将`str`作为参数传递给它来计算字符串开头的空格数。最后输出结果的代码如下所示:


std::cout << "Leading spaces: " << count << std::endl;

如果我们运行上述程序,我们将会得到如下输出:


Leading spaces: 5

这表明,字符串`str`开头的空格数为5。因此,我们可以使用上述技巧来在C++中计算字符串开头的空格数。

  
  

评论区

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