Ok so I was doing a coding challenge on codewars.com and the challenge was to take a string as input and return a string where in place of the letters are instead the number of the alphabet that matches the letter.
Everything except letters are to be ignored.
ex: "aab" would return "1 1 2"
There should be a space between each number that represents a letter in the alphabet.
So, when I run this code on my IDE (which is xcode using c99) Everything looks good and the strcmp() function says the 2 strings are equal.
The website I'm on uses C11 I believe but I don't see that causing the error.
When I run this code on the challenge website it passes a couple of tests but then fails a couple also. It fails when the input string is "", and it also fails on the string that I have used in the code below, but again it does not fail when I run it on my ide.
My questions are:
1) Any idea what is causing this bug?
2) What would you have done differently as far as the code is concerned
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *alphabet_position(char *text)
{
int i,letter_position;
unsigned long int size = strlen(text);
char *result = malloc(sizeof(int)*size + 1);
char int_string[10];
char temp = ' ';
//If String wasn't blank
if (strcmp(text, "")!=0)
{
for (i=0; i<size-1; i++)
{
//If it is a letter
if (isalpha(text[i]))
{
temp = tolower(text[i]);
if (temp == 'a')
strcat(result, "1");
else
{
letter_position = temp - 'a' + 1;
sprintf(int_string,"%d",letter_position);
strcat(result, int_string);
}
//Print space after letter until the last letter
if (i!=size-2)
strcat(result, " ");
}
}
strcat(result, "\0");
return result;
}
else
{
strcat(result, "\0");
return result;
}
}
int main(void)
{
char *string = alphabet_position("The narwhal bacons at midnight.");
char *expected_output = "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20";
printf("Your output %s\n", alphabet_position("The narwhal bacons at midnight."));
printf("Expt output %s\n", "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20");
printf("\n");
printf("your len %lu\n", strlen(alphabet_position("The narwhal bacons at midnight.")));
printf("Expt len %lu\n", strlen(expected_output));
if (strcmp(string, expected_output)==0)
printf("Equal\n");
else
printf("Not equal\n");
return 0;
}
result, sostrcat(result, "1");causes undefined behavior.size-1? You're ignoring the last character of the input string.strcat(result, "\0");. All the previous calls tostrcat()will add a null terminator.temp == 'a'? Your general calculationtemp - 'a' + 1will work for it.result[0] = 0after the malloc. This will make it a null terminated empty string that you can then pass to 'strcat'