0

I'm writing a function in C that takes a string of letters as an input and returns a string of numbers for the number position in the alphabet. I think I'm on the right track on making it which you can tell me if I'm not as I'm a complete noob to programming in general but my main question is why is my function returning weird symbols instead of numbers?

EDIT: Changed to strlen as suggested.

I'm doing a question off of codewars.com

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1, "b" = 2, etc.

Example alphabet_position("The sunset sets at twelve o' clock.") Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )

#include <stdlib.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>

// returned string has to be dynamically allocated and will be freed by the caller
char *position(const char *text) {
  //dynamically allocated array.
  char *ptr = malloc(strlen(text));
  //letters to be checked.
  char letters[] = "abcdefghijklmnopqrstuvwxyz";
  //letter positions in the alphabet.
  int pos[26] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
  //iterate through text
for(int j = 0; j < strlen(text); j++){ 
  //iterate through letters 
    for(int i = 0; i < strlen(text); i++){
      //check which letter and assign its position
        if(tolower(text[j]) == letters[i]){
            ptr[j] = (char)pos[i];
        }//if not a letter then skip over
        else {
            continue;
        }
    }
}

 

  return ptr ;
}

int main(){

char statement[] = "The narwhal bacons at midnight.";
  
printf("%s", position(statement));

}

I expected my function to return the number position of each letter in the alphabet that was given in the input of my function.

  • 1
    `sizeof(*text)` is the same as `sizeof(char)`so `sizeof(*text)/sizeof(char)` is always 1. Use `strlen()` to get the length of a string, not `sizeof`. – Barmar Mar 02 '23 at 21:06
  • @Barmar: There's a lot more wrong here than that. `ptr[j] = (char)pos[i];` is assigning low (1-26) integer values to something eventually interpreted as an ASCII string thanks to `%s` printing, so even when the sizes are right, this prints largely non-printable ASCII garbage. – ShadowRanger Mar 02 '23 at 21:10
  • And, since SP and '.' are not "translated", nothing is assigned to those positions in the resulting array meaning those values may be anything. – Fe2O3 Mar 02 '23 at 21:15

0 Answers0