21xrx.com
2024-09-20 05:45:11 Friday
登录
文章检索 我的文章 写文章
C++字符串长度比较方法
2023-07-03 08:21:52 深夜i     --     --
C++ 字符串长度 比较方法 字符串比较 strlen()函数

C++中,我们经常需要比较两个字符串的长度。在这里,我们将详细讨论三种比较字符串长度的方法。

1.使用strlen函数

strlen()是C++头文件 中的函数,它可以用来计算一个字符串的长度。代码如下:


#include <iostream>

#include <string.h>

using namespace std;

int main()

{

  char str1[] = "Hello World!";

  char str2[] = "Goodbye";

  

  int len1 = strlen(str1);

  int len2 = strlen(str2);

  

  if (len1 > len2)

    cout << "str1 is longer than str2";

  else if (len2 > len1)

    cout << "str2 is longer than str1";

  else

    cout << "str1 and str2 are of equal length";

  

  return 0;

}

2.使用size函数

我们也可以使用string类的成员函数size()来计算字符串的长度。代码如下:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1 = "Hello World!";

  string str2 = "Goodbye";

  

  int len1 = str1.size();

  int len2 = str2.length();

  

  if (len1 > len2)

    cout << "str1 is longer than str2";

  else if (len2 > len1)

    cout << "str2 is longer than str1";

  else

    cout << "str1 and str2 are of equal length";

  

  return 0;

}

在使用上述代码时,需要在程序开头添加头文件

3.使用迭代器

C++中也可以使用迭代器来计算字符串长度。迭代器是一种广泛使用的STL工具,它允许我们遍历容器中的元素。代码如下:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1 = "Hello World!";

  string str2 = "Goodbye";

  

  int len1 = 0;

  for (auto it = str1.begin(); it != str1.end(); it++)

    len1++;

  

  int len2 = 0;

  for (auto it = str2.begin(); it != str2.end(); it++)

    len2++;

  

  if (len1 > len2)

    cout << "str1 is longer than str2";

  else if (len2 > len1)

    cout << "str2 is longer than str1";

  else

    cout << "str1 and str2 are of equal length";

  

  return 0;

}

在上述代码中,我们使用std::string的begin()和end()函数创建了迭代器,然后使用auto关键字为其指定类型。对于每个字符串,我们使用迭代器来遍历字符串的每个字符,并增加它的长度。

结论

上述三种方法计算字符串长度的结果相同,且都可以达到我们所需的目的。总的来说,我们在不同的场合中可以选择不同的方法。如果我们正在使用C字符串,那么我们应该使用strlen()函数。在使用C++中的string类时,我们应该使用size()或length()函数,它们在效率和可读性方面都很好。如果使用迭代器可以帮助我们直观的了解到遍历容器的所有元素,特别是当我们需要使用其他STL算法时。

  
  

评论区

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