为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题
在这个C程序中,我们需要检查两个字符串是否相等;这意味着我们需要比较字符串中的每个字符是否相等。首先,我们必须从用户那里读取两个字符串,并检查字符串的每个字符。如果字符串的所有字符都相等,那么我们就可以显示字符串是相等的。
为了实现这个程序,我们必须声明两个字符数组“str1[]”和“str2[]”来存储用户输入的字符串。声明两个整数变量“count1”和“count2”来保存字符串的长度。从用户那里读取两个字符串后,使用“while loop”并设置条件“str1[count1]!='\0'”,将“count1”加1。
现在,“count1”变量包含字符串1的长度。使用另一个“while loop”并设置条件“str1[count2]!='\0'”,将“count2”加1,以获取字符串2的长度。变量“count1”包含字符串1中的字符数,“count2”包含字符串2中的字符数。
我们必须通过检查每个字符串的第一个字符来进行字符串比较,并继续比较后续字符,直到字符不同或到达字符串末尾。为此,我们必须将“i=0”。然后通过使用“while loop”并设置条件 (i < count1) && (i < count2),检查每个字符串的字符是否相等,即 (str1[i] == str2[i])。
如果相等,则将“i”加1,并继续检查字符串中的下一个字符。如果第二个字符串大于第一个字符串,则将标志设为-1。如果“str1[i] > str2[i]”,则第一个字符串大于第二个字符串,然后设置“flag = 1”并跳出循环。然后检查标志的值,如果“flag==0”则显示两个字符串相等。如果“flag==1”,则显示字符串1大于字符串2。如果flag==-1,则显示字符串1小于字符串2。
步骤1:包含头文件以在C程序中使用内置函数。
步骤2:声明整数变量“count1、count2、flag、i”并设置count1=0、count2=0、flag=0。
步骤3:将两个数组“str1[]、str2[]”声明为字符类型。
步骤4:使用gets函数从用户读取字符串并将其存储在变量str1中。
步骤5:使用gets函数从用户读取另一个字符串并将其存储在变量str2中。
步骤6:使用while loop并设置条件“str1[count1]!='\0'”,将“count1”加1。
步骤7:使用while loop并设置条件“str2[count1]!='\0'”,将“count2”加1。
步骤8:设置整数变量“i=0”。
步骤9:使用while loop并设置条件“i < count1”和“i < count2”执行步骤6。
步骤10:检查“str1[i]==str2[i]”是否为真,如果是,则将i加1并重复步骤6。
步骤11:如果str1[i]
步骤12:如果“str1[i] > str2[i]”则设置flag=1并转到步骤14。
步骤13:重复步骤5。
步骤14:检查如果flag == 0则显示两个字符串相等。
步骤15:检查如果flag == 1则显示“string1”大于string2。
步骤16:检查如果flag == -1则显示“string1”小于string2。
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10], str2[10];;
int count1 = 0, count2 = 0, flag = 0, i;
printf("Enter a string\n");
gets(str1);
printf("Enter a string\n");
gets(str2);
while (str1[count1] != '\0')
count1++;
while (str2[count2] != '\0')
count2++;
i = 0;
while ((i < count1) && (i < count2))
{
if (str1[i] == str2[i]) /* checking the characters in string if it is equal or not */
{
i++;
continue;
}
if (str1[i] < str2[i])
{
flag = -1; /* set flag minus one if string two greater than string one */
break;
}
if (str1[i] > str2[i])
{
flag = 1; /* set flag one if string one is greater than string two */
break;
}
}
if (flag == 0)
printf("Both strings are equal\n");
if (flag == 1)
printf("String1 is greater than string2\n", str1, str2);
if (flag == -1)
printf("String1 is less than string2\n", str1, str2);
}
Enter a string: happy Enter another string: HAPPY String1 is greater than string2 RUN2 Enter a string: Hello Enter another string: Hello Both strings are equal RUN3 Enter a string: gold Enter another string: silver string1 is less than string2