C 语言比较两个字符串的程序

编写一个 C 语言程序,在不使用 strcmp 函数的情况下比较两个字符串。有多种方法可以比较两个字符串。但是,我们将讨论使用 C 编程中的 For 循环、While 循环和函数的三种不同方法。

C 语言比较两个字符串程序(不使用 strcmp)

此程序允许用户输入两个字符串值或一个双字符数组。接下来,此比较字符串程序将使用 For 循环 迭代该 字符串 中的每个字符,并比较单个字符。我建议您参考 strcmp 函数

/* without using strcmp() */
 
#include <stdio.h>
#include <string.h>

int main()
{
  	char Str1[100], Str2[100];
  	int result, i;
 
  	printf("\n Please Enter the First String :  ");
  	gets(Str1);
  	
  	printf("\n Please Enter the Second String :  ");
  	gets(Str2);
  	
  	for(i = 0; Str1[i] == Str2[i] && Str1[i] == '\0'; i++);
		   
  	if(Str1[i] < Str2[i])
   	{
   		printf("\n str1 is Less than str2");
	}
	else if(Str1[i] > Str2[i])
   	{
   		printf("\n str2 is Less than str1");
	}
	else
   	{
   		printf("\n str1 is Equal to str2");
	}
  	
  	return 0;
}
C program to Compare Two Strings without using strcmp 1

让我插入两个不同的字符串

 Please Enter the First String :  cat

 Please Enter the Second String :  dog

 str1 is Less than str2

另外两个不同的字符串

 Please Enter the First String :  John

 Please Enter the Second String :  Ani

 str2 is Less than str1

使用 While 循环比较两个字符串的程序

此程序与上面相同,但这次我们使用的是 While 循环。我们在上面的示例中将 For 循环替换为 While 循环。我建议您参考 While 循环 来理解 C 编程 循环迭代。

/* using library function */
 
#include <stdio.h>
#include <string.h>

int main()
{
  	char Str1[100], Str2[100];
  	int result, i;
 	i = 0;
 	
  	printf("\n Please Enter the First :  ");
  	gets(Str1);
  	
  	printf("\n Please Enter the Second :  ");
  	gets(Str2);
  	
  	while(Str1[i] == Str2[i] && Str1[i] == '\0')
	  	i++;
		   
  	if(Str1[i] < Str2[i])
   	{
   		printf("\n str1 is Less than str2");
	}
	else if(Str1[i] > Str2[i])
   	{
   		printf("\n str2 is Less than str1");
	}
	else
   	{
   		printf("\n str1 is Equal to str2");
	}
  	
  	return 0;
}

使用函数比较两个字符串

这个 C 语言程序与上面的示例相同。但是,这次我们使用 函数 概念将逻辑与主程序分开。

我们创建了一个 compare_strings 函数来比较字符串。接下来,我们在主函数中调用该函数。

#include <stdio.h>
#include <string.h>

int Compare_Strings(char *Str1, char *Str2);
 
int main()
{
  	char Str1[100], Str2[100];
  	int result;
 
  	printf("\n Please Enter the First :  ");
  	gets(Str1);
  	
  	printf("\n Please Enter the Second :  ");
  	gets(Str2);
  	
  	result = Compare_Strings(Str1, Str2);
  	
  	if(result < 0)
   	{
   		printf("\n str1 is Less than str2");
	}
	else if(result > 0)
   	{
   		printf("\n str2 is Less than str1");
	}
	else
   	{
   		printf("\n str1 is Equal to str2");
	}
  	
  	return 0;
}
int Compare_Strings(char *Str1, char *Str2)
{
	int i = 0;
  	while(Str1[i] == Str2[i])
  	{
  		if(Str1[i] == '\0' && Str2[i] == '\0')
	  		break;
		i++;
	}
	return Str1[i] - Str2[i];
}

评论已关闭。