21xrx.com
2024-09-19 23:53:18 Thursday
登录
文章检索 我的文章 写文章
C++字符串长度比较方法
2023-07-05 05:23:20 深夜i     --     --
C++ 字符串 长度比较 方法

在C++中,比较字符串长度通常使用标准库中的函数strlen()。这个函数需要传入一个字符串参数,并返回这个字符串参数的长度(不包括字符串末尾的'\0')。

例如,如果要比较两个字符串的长度大小,可以先使用strlen()函数分别计算出它们的长度,然后再进行比较:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "hello";

  char str2[] = "world";

  int len1 = strlen(str1);

  int len2 = strlen(str2);

  if(len1 > len2)

    cout << "str1 is longer than str2." << endl;

  else if(len1 < len2)

    cout << "str2 is longer than str1." << endl;

  else

    cout << "str1 and str2 have the same length." << endl;

  return 0;

}

输出结果为:str2 is longer than str1.。

另外,在C++11及以上版本中,也可以使用字符串类std::string中的成员函数length()来获取字符串长度。同样,也可以使用它来比较字符串长度大小:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1 = "hello";

  string str2 = "world";

  if(str1.length() > str2.length())

    cout << "str1 is longer than str2." << endl;

  else if(str1.length() < str2.length())

    cout << "str2 is longer than str1." << endl;

  else

    cout << "str1 and str2 have the same length." << endl;

  return 0;

}

输出结果与前面的示例相同:str2 is longer than str1.。

  
  

评论区

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