Home > other >  Shifting letters in a word alphabetically
Shifting letters in a word alphabetically

Time:04-03

I'm currently working a project involving shifting letters in a word and further working with all possible outcomes.

It should work like this: e.g:

helloworld ifmmpxpsme jgnnqyqtnf

...and so on. Since I'm new to programming and quite stuck on this matter, could anyone please give me a hint on how to successfully manage just that ? I know it can't be that difficult and it maybe has something to do with ASCII letter representation, however, I don't know, how to perform this. Thanks in advance for your kind help.

CodePudding user response:

You should try reading this site, it shows the ASCII table very clearly.

In ASCII very character was its own unique value for example 'T' is equal to 84 and 't' is equal to 116. So, if we add 1 to them it will become 'S' and 's' respectively and same logic goes for -1.

Code

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

static char *shift(const char *word)
{
    if (!word)
        return NULL;
    char *ptr = calloc(strlen(word)   1, sizeof(char));
    if(!ptr)
        return NULL;
    for (size_t i = 0; word[i]; i  )
    {
        if (!isalpha(word[i]))
            return NULL;
        ptr[i] = word[i]   1;
    }
    return ptr;
}

int main(void)
{
    char *word = shift("helloworld");
    while (word)
    {
        puts(word);
        word = shift(word);
    }
    return EXIT_SUCCESS;
}

Output:

ifmmpxpsme
jgnnqyqtnf
khoorzruog
lipps{svph
  • Related