C语言程序:检查两个字符串是否相同
给定两个字符串str1和str2,我们必须检查这两个字符串是否相同。例如,我们给出两个字符串“hello”和“hello”,它们是相同的。
相同的字符串看起来相等,但实际上不相等,例如:“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()并将两个字符串作为参数传递。
- 如果返回零,则打印“Yes, 两个字符串相同”。
- 否则打印“No, 两个字符串不同”。
算法
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
" Step 3-> else Print "No, 2 strings are not same
" Stop
示例
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
char string1[] = {"tutorials point"};
char string2[] = {"tutorials point"};
//using function strcmp() to compare the two strings
if (strcmp(string1, string2) == 0)
printf("Yes 2 strings are same
");
else
printf("No, 2 strings are not same
" );
return 0;
}输出
如果运行以上代码,将生成以下输出:
Yes 2 strings are same
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP