In my code, I used a tolower function in order to eliminate letters not considering their cases. ( case insensitive) but my problem is that if my first input is "HELLO" and my 2nd is "hi" the ouput would be "ello" in lowercase letters instead of "ELLO". Is there any way to fix this? Should I not use tolower function?
#include <stdio.h>
#include <conio.h>
void main()
{
char s1[20],s2[20];
int i,j;
printf("\nEnter string 1:- ");
gets(s1);
printf("\nEnter the string for matching:- ");
gets(s2);
for(int i = 0; s1[i]; i )
{
s1[i] = tolower(s1[i]);
}
for(int i = 0; s2[i]; i )
{
s2[i] = tolower(s2[i]);
}
for (i=0;(i<20&&s1[i]!='\0');i )
{
for (j=0;(j<20&&s2[j]!='\0');j )
{
if (s1[i]==s2[j])
s1[i]=' ';
}
}
printf("\nString 1 after deletion process is %s",s1);
printf("\nIts compressed form is ");
for (i=0;(i<20&&s1[i]!='\0');i )
{
if (s1[i]!=' ')
printf("%c",s1[i]);
}
getch();
}
CodePudding user response:
I ran the exact same code which you are using.
CodePudding user response:
Your code has security vulnerabilities because you're using gets() (if the text input by the user is larger than 19 bytes, you'll have buffer overflows on variables s1 and s2). This function is bugged, it's not fixable and should never be used. Instead use, for example, fgets(s1, sizeof(s1), stdin).
The main idea of the problem is that you must preserve the strings, so remove the loops that modify them. In this case the correct predicate for checking if each compared character is the same without regard to case would become:
if (tolower(s1[i]) == tolower(s2[j]))
CodePudding user response:
- Write a function
- Compare the results of tolower() directly — don’t change the strings themselves
- Do not use
gets()andscanf("%s")— both have no bounds checking
EDIT: sorry, this function simply compares two strings. It is meant to give you an idea of how to use tolower() effectively, not do your work for you. :-)
#include <iso646.h>
#include <ctype.h>
bool is_equal( const char * a, const char * b )
{
while (*a and *b)
{
if (tolower( *a ) != tolower( *b ))
return false;
}
if (*a or *b) return false;
return true;
}
Now you can call the function directly.
if (is_equal( "HELLO", "hello" )) ...
Getting a string input from the user in C is always a pain, but you can use fgets() for that.
char s[100]; // the target string (array)
fgets( s, 100, stdin ); // get max 99 characters with null terminator
char * p = strchr( s, '\n' ); // find the Enter key press
if (p) *p = '\0'; // and remove it
puts( s ); // print the string obtained from user
You can always wrap all the annoying stuff for getting strings into a function.

