I made a function to find out if two words are anagrams... But I didn't want to modify the two original strings. And my function modifies one of the strings, the string that I lower in an char
auxiliary * ( sAux
) (I did it precisely so as not to modify the original string). In my opinion, the auxiliary pointer is pointing to the same place as the pointer that arrives as a parameter to the function (the one of the string that I do not want to modify). But I can't figure out how to fix it.
I show you the function. The string that is modified is the call s1
( const char*s1
-parameter that the function receives). Note that I must not modify the original strings and must use pointer arithmetic.
int esAnagrama(const char *s1, const char *s2)//s1 se modifica
{
char*sAux=(char*)s1,*s2Aux=sAux;//puedo observar que apuntan a lo mismo- a la misma direccion de memoria.
int i=0,j=0,k=0;
while(*(sAux+i)&&*(s2+k))
{
if((*(sAux+i)!=*(s2+k))&&*(s2+k)!=' '&&*(sAux+i)!=*(s2+k)+32&&*(sAux+i)!=*(s2+k)-32)
{
if(*(sAux+i)!=' ')
{
*(s2Aux+j)=*(sAux+i);///si no encontro la letra la dejo en s2aux
j++;
}
}
else k++;//si encontro la letra sigo recorriendo la cadena
i++;
if(*(sAux+i)=='\0'&&i!=j)
{
*(s2Aux+j)='\0';
sAux=s2Aux;
i=j=0;
}
}
return(!*(s2+k)&&!*(sAux+i));
}
Any suggestions on how to fix it so that the s1
original string is not modified? I tried to allocate memory for the char*
one where I lowered the original string but it gave the result I expected.
Easy, create a temporary string inside the function:
Of course. The surprising thing is that to check if you have found an anagram you modify the input data, it is not necessary! Let's see what an anagram is :
Since you need to count the letters in both strings, let's create two count buffers:
These two buffers have one position for each possible letter. The next thing we need to know is that if the incoming strings don't have the same length they can't possibly be anagrams, so we count their length:
Knowing this, we loop through both strings at once counting the letters in each:
I lowercase the letter a so that (for example) " Mary " and " Army " count as an anagram. Once this is done, if both words are anagrams the buffers will be the same:
As you can see, it has not been necessary to modify any of the input strings, this would be the complete code:
You can see it working in Wandbox 三へ( へ՞ਊ ՞)へ ハッハッ.
Note that the code I have shared will not consider sentences with the same amount of letters but different spacing as " Tom Marvolo Riddle " with " I am Lord Voldemort " as anagrams. It could be left to you as an additional exercise to solve this problem.