Module 16 - Lesson 14 ► Compare two strings without using inbuilt functions [Learn Programming]

preview_player
Показать описание
Develop your programming logic, by learning about basics in C Programming. This is our series in step by step video based series.

=======================================
● 101 Programs to Build Your Programming Logic
=======================================

==============================
● Lets stay in touch!
==============================
Рекомендации по теме
Комментарии
Автор

Here is the extended version of the above program, compiled on GCC compiler


#include <stdio.h>
#include <stdlib.h>




void compareStrings(char *longer, char *shorter, char* longerStringName, char* shorterStringName)
{


//Now compare strings character by character
while(*longer!='\0')
{
if(*longer != *shorter)
{
if(*longer > *shorter || *shorter == '\0')
printf("%s is greater\n", longerStringName);
else
printf("%s is greater\n", shorterStringName);
exit(0);
}


longer++;
shorter++;
}
}




int main()
{
char str1[100], str2[100];
char *ptr1, *ptr2, *longer, *shorter;
int len1 = 0, len2 = 0;


printf("Enter a string 1: ");
scanf("%s", str1);
printf("Enter a string 2: ");
scanf("%s", str2);
//assign address of str to ptr
ptr1 = str1;
ptr2 = str2;

//identify which one is the longest string


while(*ptr1!='\0')
{
len1++;
ptr1++;
}


while(*ptr2!='\0')
{
len2++;
ptr2++;
}




//Indetify longer and shorter string
if(len1 > len2)
printf("String 1 is greater in length\n");
else if(len1 < len2)
printf("String 2 is greater in length\n");
else
printf("Strings are equal in length\n");


//Now let's compare character by character
if(len1 > len2)
compareStrings(str1, str2, "String 1", "String 2");
else
compareStrings(str2, str1, "String 2", "String 1");


//If execution reaches this point that means strings are equal.
printf("Strings are equal\n");




return 0;
}

kodegod