C程序检查两个字符串是否相同

给定两个字符串str1和str2,我们必须检查两个字符串是否相同。就像我们给了两个字符串“你好”和“你好”一样,它们是相同的。

看起来相同但不相等的字符串相同:“ Hello”和“ hello”,完全相同的字符串相同:“ World”和“ World”。

示例

Input: str1[] = {“Hello”}, str2[] = {“Hello”}
Output: Yes 2 strings are same
Input: str1[] = {“world”}, str2[] = {“World”}
Output: No, 2 strings are not same

下面使用的方法如下-

我们可以使用strcmp(string2,string1)。

strcmp()字符串比较函数是“ string.h”头文件的内置函数,该函数接受两个参数,两个字符串。此函数比较两个字符串,并检查两个字符串是否相同,如果字符串没有变化,则返回0;如果两个字符串不相同,则返回非零值。此函数区分大小写,这意味着两个字符串应该完全相同。

  • 因此,我们将两个字符串作为输入。

  • 使用strcmp()并传递两个字符串作为参数

  • 如果它们返回零,则打印“是,两个字符串相同”

  • 否则打印“不,两个字符串不相同”。

算法

Start
In function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize 2 strings string1[] and string2[]
   Step 2-> If strcmp(string1, string2) == 0 then,
      Print "Yes 2 strings are same\n"
   Step 3-> else
      Print "No, 2 strings are not same\n"
Stop

示例

#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
   char string1[] = {"nhooo.com"};
   char string2[] = {"nhooo.com"};
   //using function strcmp() to compare the two strings
   if (strcmp(string1, string2) == 0)
      printf("Yes 2 strings are same\n");
   else
      printf("No, 2 strings are not same\n" );
      return 0;
}

输出结果

如果运行上面的代码,它将生成以下输出-

Yes 2 strings are same