21xrx.com
2024-09-20 00:31:15 Friday
登录
文章检索 我的文章 写文章
如何在C++中判断字符数组是否相等?
2023-07-05 00:46:53 深夜i     --     --
C++ 字符数组 判断 相等

在C++中,要判断两个字符数组是否相等,可以使用strcmp()函数或自己写一个比较函数。

strcpy()函数是C++自带的字符串处理函数,可以用来比较两个字符数组是否相等。该函数的定义如下:

int strcmp(const char* str1, const char* str2);

该函数有两个参数,分别是要比较的两个字符数组。返回值为整型,表示两个字符数组比较的结果。如果字符串相等,则返回0;如果第一个字符串大于第二个字符串,则返回一个正整数;如果第二个字符串大于第一个字符串,则返回一个负整数。

下面是一个使用strcmp()函数判断两个字符数组是否相等的例子:

#include

#include

using namespace std;

int main()

{

  char str1[] = "Hello";

  char str2[] = "world";

  char str3[] = "Hello";

  if (strcmp(str1, str2) == 0)

    cout << "str1 is equal to str2" << endl;

  else

    cout << "str1 is not equal to str2" << endl;

  if (strcmp(str1, str3) == 0)

    cout << "str1 is equal to str3" << endl;

  else

    cout << "str1 is not equal to str3" << endl;

  return 0;

}

输出结果为:

str1 is not equal to str2

str1 is equal to str3

除了使用strcmp()函数,我们也可以自己编写一个比较函数,来判断两个字符数组是否相等。下面是一个自定义的比较函数例子:

#include

#include

using namespace std;

bool isEqual(char a[], char b[], int length)

{

  for (int i = 0; i < length; i++)

  {

    if (a[i] != b[i])

      return false;

  }

  return true;

}

int main()

{

  char str1[] = "Hello";

  char str2[] = "world";

  char str3[] = "Hello";

  if (isEqual(str1, str2, strlen(str1)))

    cout << "str1 is equal to str2" << endl;

  else

    cout << "str1 is not equal to str2" << endl;

  if (isEqual(str1, str3, strlen(str1)))

    cout << "str1 is equal to str3" << endl;

  else

    cout << "str1 is not equal to str3" << endl;

  return 0;

}

输出结果为:

str1 is not equal to str2

str1 is equal to str3

无论是使用strcmp()函数还是自定义比较函数,都需要注意字符数组的长度。如果两个字符数组长度不同,即使内容相同,也会被判断成不相等。所以需要在比较前先确定字符数组的长度。

  
  

评论区

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