Home > OS >  How to shift characters in a String in C?
How to shift characters in a String in C?

Time:11-21

How can I shift characters in a string to the right? For Example I want to shift every letter of "Hello" 3 times to the right. The ending letter starts at the beginning. So the output should be "lloHe".

I tried to do it with a pointer. But the output is just "k". The program just takes the "h" from the hello and shifts it 3 digits to the right from the alphabet. But thats not what I intended to do. Any tips you can give me?

#include <stdio.h>


int main () {
    int a[5] = {'h','e','l', 'l','o','\0'};
    char i;
    char ptr;

    ptr = a;
    printf ("%c\n",ptr 3);

    return 0;

}

CodePudding user response:

Do you actually want to manipulate the data, or just produce the output? You could do something like:

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

int
main(int argc, char **argv)
{
    char a[] = {'h', 'e', 'l', 'l', 'o', '\0'};  /* Note the [], and the type */
    char i;
    char *ptr;    /* Note the '*'; ptr is a pointer */

    ptr = a;
    int shift = argc > 1 ? strtol(argv[1], NULL, 10) : 3;

    shift %= sizeof(a);

    printf("%s", ptr   shift);   /* Note the %s */
    fwrite(a, 1, shift, stdout);
    putchar('\n');

    return 0;
}

Usually, the initialization would be written char a[] = "hello";, and if you make a an array of int, you cannot use printf to do output. If you need a to be ints for some reason, you could do:

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

int
main(int argc, char **argv)
{
    int a[] = {'h','e','l', 'l','o','\0'};
    int shift = argc > 1 ? strtol(argv[1], NULL, 10) : 3;
    shift %= sizeof a  / sizeof *a;
    int *ptr = a   shift;

    /* Print the tail of the string */
    while( ptr < a   sizeof a / sizeof *a ){
        putchar(*ptr  );
    }
    /* Print the head of the string */
    ptr = a;
    while( ptr < a   shift ){
        putchar(*ptr  );
    }
    putchar('\n');
    return 0;
}

CodePudding user response:

int a[5] = ...
char ptr;
ptr = a;

Here a is a pointer to int. Assigning it to a variable of type char is not a correct thing to do. Compilers should emit a warning on that. Don't ignore warnings: they usually indicate that there is something wrong in your code!

You probably intended to use int * instead of char:

int a[5] = ...
int *ptr;
ptr = a;

With this code, shifting the pointer will work: ptr 3 does what you want.


To print one character at a pointer, dereference the pointer first:

printf ("%c\n", *(ptr 3)); // alternative spelling: ptr[3]

If you don't dereference, the compiler will warn you that the code is incorrect.

  •  Tags:  
  • c
  • Related