Reputation: 13
I am new to coding and started to learn strings in C (you might find a lot of mistakes in my code but I am still trying to learn from my mistakes).
I am trying to write a code that takes 2 strings and check for intersection between the 2 strings and then returns the count of identical indexes; right now, the problem with this code is that it prints out extra space in output and does not calculate it right.
I believe it checks each index with the whole string looking for identical match, but I want it to only check indexes according to their places.
E.g., for input :
str1: Abc 1223 $#& cDE\0
str2: AB 12 34 #$ c\0
the output should be:
Found 6 Matches. (in this case they are index numbers(0,1,6,9,11,12))
Here's the Faulty code I came up with so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define MAX 80
int main()
{
char str1[MAX];
char str2[MAX];
int i = 0, j = 0;
int Counter = 0;
printf("Enter Your First String : \n ");
gets(str1);
printf("Enter Your Second String : \n ");
gets(str2);
while (str1[i] != '\0' && str2[i] != '\0')
{
if (str1[i] >= 65 && str1[i] <= 90)
{
str1[i] = str1[i] + 32;
}
if (str2[i] >= 65 && str2[i] <= 90)
{
str2[i] = str2[i] + 32;
}
if (str1[i] = str2[i])
{
Counter++;
}
i++;
}
printf("Similarities Between 2 Strings Count Is : %d \n", Counter);
return 0;
}
Upvotes: 1
Views: 588
Reputation: 51835
The main issue with your code is the if (str1[i] = str2[i])
line. This uses the assignment operator (=
), thus giving str1[i]
the value in str2[i]
. What you need, instead, is the comparison operator (==
):
if (str1[i] = str2[i])
{
Counter++;
}
Also, be aware that the gets
function has long been declared unsafe and removed from the standard library. Use fgets
instead, specifying the length of your input arrays and the stdin
'file' for input:
printf("Enter Your First String : \n ");
fgets(str1, MAX, stdin);
printf("Enter Your Second String : \n ");
fgets(str2, MAX, stdin);
Another issue with your code (though not really an error) is the use of so-called "magic numbers" for your lowercase letter checks. It is better to use the actual characters (as literals) in such cases. Thus, instead of:
if (str1[i] >= 65 && str1[i] <= 90)
//...
using this is much clearer:
if (str1[i] >= 'a' && str1[i] <= 'z')
//...
But you should really consider using the toupper()
and/or islower()
functions, here.
Upvotes: 1