Compare and change case of two strings - C

Q. Write a C program to accept two strings and compare. If the strings are equal, display length of string.

If str1 > str2, convert str1 to uppercase and str2 to lowercase.


Solution:

#include<stdio.h>
#include<string.h>
int main()
{
    char str1[30],str2[30];
    int length,i;
    printf("Enter String-1: ");
    scanf("%s",str1);
    printf("\nEnter String-2: ");
    scanf("%s",str2);
    if(strcmp(str1,str2)==0)
    {
        length=strlen(str1);
        printf("String are Equal and Length is %d.",length);
    }
    else if(strcmp(str1,str2)>0)
    {
        printf("\nString-1 is Greater");
        for(i=0;i<=strlen(str1);i++)
        {
            if(str1[i]>=97&&str1[i]<=122)
                str1[i]=str1[i]-32;
        }
        printf("\n\nString-1 in Uppercase: %s",str1);
        for(i=0;i<=strlen(str2);i++)
        {
            if(str2[i]>=65&&str2[i]<=90)
            str2[i]=str2[i]+32;
        }
        printf("\n\nString-2 in Lower Case: %s",str2);
    }
    else
    {
        printf("\nString2 is Greater");
        for(i=0;i<=strlen(str2);i++)
        {
            if(str2[i]>=97&&str2[i]<=122)
            str2[i]=str2[i]-32;
        }
        printf("\n\nString-2 in Uppercase: %s",str2);
        for(i=0;i<=strlen(str1);i++)
        {
            if(str1[i]>=65&&str1[i]<=90)
                str1[i]=str1[i]+32;
        }
        printf("\n\nString-1 in Lowercase: %s",str1);
    }
    return 0;
}


Q. Write a C program to accept two strings and compare. If the strings are equal, display length of string.

If str1 > str2, convert str1 to uppercase and str2 to lowercase.

Use functions.


Solution:

In this program, use character functions toupper & tolower. These functions are included in header file ctype.h.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
    char str1[30],str2[30];//ch;
    int length,i;
    printf("Enter String-1: ");
    scanf("%s",str1);
    printf("\nEnter String-2: ");
    scanf("%s",str2);
    if(strcmp(str1,str2)==0)
    {
        length=strlen(str1);
        printf("\nString are Equal and Length is %d",length);
    }
    else if(strcmp(str1,str2)>0)
    {
        printf("\nString-1 is Greater.");
        printf("\n\nString-1 in Uppercase: ");
        for(i=0;str1[i]!='\0';i++)
        {
            //ch=toupper(str1[i]);
            //printf("%c",ch);
            putchar(toupper(str1[i]));
        }
        printf("\n\nString-2 in Lower Case: ");
        for(i=0;str2[i]!='\0';i++)
        {
            putchar(tolower(str2[i]));
        }
    }
    else
    {
        printf("\nString-2 is Greater.");
        printf("\n\nString-2 in Uppercase:");
        for(i=0;str2[i]!='\0';i++)
        {
            putchar(toupper(str2[i]));
        }
        printf("\n\nString-1 in Lowercase: ");
        for(i=0;str1[i]!='\0';i++)
        {
            putchar(tolower(str1[i]));
        }
    }
    return 0;
}


Output:

compare convert two strings