21xrx.com
2024-05-20 16:45:27 Monday
登录
文章检索 我的文章 写文章
C++中如何比较两个字符串?
2023-07-09 20:22:59 深夜i     --     --
C++ 字符串 比较

在C++中,比较两个字符串可以使用一些函数或操作符来实现。下面介绍几种常用的方法。

1. strcmp函数

strcmp函数可以用来比较两个字符串。它的函数原型是:

int strcmp(const char *s1, const char *s2);

该函数会将字符串s1和s2逐个字符比较,直到出现不同的字符或者遇到'\0'结束符为止。如果s1等于s2,则该函数返回0;如果s1小于s2,则返回负数;如果s1大于s2,则返回正数。示例如下:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "hello";

  char str2[] = "world";

  int cmp = strcmp(str1, str2);

  if (cmp == 0)

    cout << "str1 equals str2" << endl;

   else if (cmp < 0)

    cout << "str1 is less than str2" << endl;

   else

    cout << "str1 is greater than str2" << endl;

  

  return 0;

}

输出结果为:


str1 is less than str2

2. string类的比较操作符

在C++中,也可以使用string类的比较操作符(==、!=、<、<=、>、>=)来比较两个字符串。示例如下:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1 = "hello";

  string str2 = "world";

  if (str1 == str2)

    cout << "str1 equals str2" << endl;

   else if (str1 < str2)

    cout << "str1 is less than str2" << endl;

   else

    cout << "str1 is greater than str2" << endl;

  

  return 0;

}

输出结果为:


str1 is less than str2

3. strncmp函数

strncmp函数与strcmp函数类似,不同之处在于它可以比较指定长度的字符串。其函数原型为:

int strncmp(const char *s1, const char *s2, size_t n);

该函数会将字符串s1和s2前n个字符逐个比较,直到出现不同的字符或者遇到'\0'结束符为止。如果s1等于s2,则该函数返回0;如果s1小于s2,则返回负数;如果s1大于s2,则返回正数。示例如下:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str1[] = "hello, world";

  char str2[] = "hello, c++";

  int cmp = strncmp(str1, str2, 5);

  if (cmp == 0)

    cout << "str1 equals str2" << endl;

   else if (cmp < 0)

    cout << "str1 is less than str2" << endl;

   else

    cout << "str1 is greater than str2" << endl;

  

  return 0;

}

输出结果为:


str1 equals str2

4. string类的compare函数

string类的compare函数也可以用来比较两个字符串。其函数原型为:

int compare(const string& str) const;

该函数会将调用该函数的字符串和参数str逐个字符比较,直到出现不同的字符或者到达字符串的结尾为止。如果调用该函数的字符串等于参数str,则返回0;如果调用该函数的字符串小于参数str,则返回负数;如果调用该函数的字符串大于参数str,则返回正数。示例如下:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1 = "hello, world";

  string str2 = "hello, c++";

  int cmp = str1.compare(str2);

  if (cmp == 0)

    cout << "str1 equals str2" << endl;

   else if (cmp < 0)

    cout << "str1 is less than str2" << endl;

   else

    cout << "str1 is greater than str2" << endl;

  

  return 0;

}

输出结果为:


str1 is greater than str2

总的来说,以上几种方法都可以用来比较两个字符串。具体使用哪种方法,可以根据实际情况选择。

  
  

评论区

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