Hello everyone! Im doing the “Anagram Finder” task in Learn C course, but I am stuck!
This are the prompts to follow:
- Create two integer arrays called
counter1
andcounter2
. Initialize both arrays with four zeros each. - We will check if the following two strings are anagrams:
- String 1: “dbb cccccaacb cdbababdcdcdab dcdad”
- String 2: “bbbcc bdddccccad cdbbaaacaccdabdd”
Right under your counters, create two char
arrays called s1
and s2
containing String 1 and String 2 respectively.
3. First, create a for
loop to loop through the string. Use strlen()
to find the length of the string.
4. We will now write the logic to determine the number of each character in String 1.
We will update counter1
in the following way:
- If we encounter an ‘a’ we will increment
counter1[0]
by one. - If we encounter a ‘b’ we will increment
counter1[1]
by one. - If we encounter a ‘c’ we will increment
counter1[2]
by one. - If we encounter a ‘d’ we will increment
counter1[3]
by one. - If we encounter a space, we ignore it.
Implement this logic in the loop body.
5. Loop through String 2 and update its counter ( counter2
) accordingly.
6. We need a flag that we can use to determine if there is a mismatch in the two counters.
First, create an integer variable called flag
and set it to 0
.
The flag variable maintains one of these states:
- The flag will be set to zero if there is no mismatch in the counters.
- The flag will be set to one if there is a mismatch in the counters
- Create an empty
for
loop that you will use to loop through both counters. We will place logic in it in the next task. - In the loop, change the
flag
variable’s value to 1 if a mismatch is encountered.
If the two strings are anagrams, print “Anagram!”. If they are not, print “Not Anagram!”
This is my code:
#include <stdio.h>
#include <string.h>
int main (){
//counters
int counter1 = {0,0,0,0};
int counter2 = {0,0,0,0};
//strings to compare and verify
char s1 = “dbb cccccaacb cdbababdcdcdab dcdad”;
char s2 = “bbbcc bdddccccad cdbbaaacaccdabdd”;
//verification process s1
for (int i = 0; i < strlen(s1); i++){
if (s1[i] == ‘a’){
counter1[0]++;
}
if (s1[i] == ‘b’){
counter1[1]++;
}
if (s1[i] == ‘c’){
counter1[2]++;
}
if (s1[i] == ‘d’){
counter1[3]++;
}
if (s1[i] == ’ '){
continue;
}
}
//verification process s2
for (int j = 0; j < strlen(s2); j++){
if (s2[j] == ‘a’){
counter2[0]++;
}
if (s2[j] == ‘b’){
counter2[1]++;
}
if (s2[j] == ‘c’){
counter2[2]++;
}
if (s2[j] == ‘d’){
counter2[3]++;
}
if (s2[j] == ’ '){
continue;
}
}
//check if they are anagrams
for (int flag = 0; flag < 4; flag++){
if (counter2[j] == counter1[i]){
flag = 0;
printf(“Anagram!”);
}
else {
printf(“Not Anagram!”);
}
}
}
This last part is where I think Im not getting it. Any help would be great. Thank you!