C language: Educoder-string size comparison

String size comparison

mission details

Write a program to compare two strings s1 and s2, if s1>s2, output a positive number, if s1=s2, output 0, if s1<s2, output a negative number. It is required that the strcmp function cannot be used. The absolute value of the output positive or negative number should be the difference between the ASCII codes of the corresponding characters of the two strings being compared. For example, comparing "A" with "C", since "A"<"C", a negative number should be output. At the same time, since the difference between the ASCII code of "A" and "C" is 2, it should output "-2". In the same way, "And" and "Aid" are compared. According to the comparison result of the second character,'n' is 5 greater than'i', so "5" should be output.
(Because the gets function is considered an unsafe function in the educoder environment, the tasks in this section adopt the standard input function to achieve the requirements, for example: scanf("%s %s",a,b); where a,b are custom Array of characters, combined with the end of the string'\0' to determine the end position of the string.)

#include<stdio.h>
#define N 100
char s1[N], s2[N];
int main()
{
    
    	
	int s = 0;
	scanf("%s%s", s1, s2);
	for(int i = 0;s1[i] || s2[i];i++)
	s += s1[i] - s2[i];
	printf("%d", s);
	return 0;
} 

Guess you like

Origin blog.csdn.net/m0_51354361/article/details/113574996