21xrx.com
2025-03-28 02:34:45 Friday
文章检索 我的文章 写文章
C++字符串个数统计
2023-07-07 12:21:47 深夜i     24     0
C++ 字符串 个数 统计

在C++中,统计字符串个数是非常基础也是非常有用的技能。在很多场合下都需要使用此技能,比如统计文本文件中某个单词的出现次数,或者编写一个程序统计某个字符串在一个字符串数组中的出现次数等等。那么,怎样在C++程序中实现此功能呢?我们可以通过以下两种方法进行操作。

方法一:使用循环判断字符串个数

这种方法比较简单,我们可以通过循环遍历的方式来判断字符串的个数。具体的实现过程如下:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  char str[] = "This is a test";
  int count = 0//字符串个数计数器
  for(int i=0; i<strlen(str); i++)
  {
    if(str[i] == ' '//判断空格
    {
      count++;  //计数器加 1
    }
  }
  cout << "字符串个数为: " << count + 1 << endl;  //输出最终结果
  return 0;
}

运行结果为:

字符串个数为: 4

可以看到,程序使用一个循环遍历整个字符串,每当遇到空格时,计数器加 1,最后输出的个数为计数器值加上 1。

方法二:使用string库函数实现

相比较方法一,这种方式显得更简单且方便,程序代码如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "This is a test";
  int count = 1//字符串个数计数器
  for(int i=0; i<str.length(); i++)
  {
    if(str[i] == ' '//判断空格
    {
      count++;  //计数器加 1
    }
  }
  cout << "字符串个数为: " << count << endl;  //输出最终结果
  return 0;
}

运行结果同样是:

字符串个数为: 4

总结

通过上面两种方法的实现,我们可以得出一个结论:在C++程序中,统计字符串个数非常容易,无论是使用循环判断还是使用string库函数实现,都可以达到同样的效果。具体哪种方式使用,可以根据实际情况自行决定。

  
  

评论区

请求出错了