tags:

views:

140

answers:

3

Greetings I am trying to find the function in the library that shifts chars back and forward as I want for instance:

if this function consumes 'a' and a number to shift forward 3 , it will be shifted 3 times and the output will be 'd'.

if it this function consumes '5' and a number to shift forward 3 , it will be shifted 3 times and the output will be '8'.

how can I achieve this?

Regards

+3  A: 

Given what you've asked for, this does that:

char char_shift(char c, int n) {
   return (char)(c + n);
}

If you meant something else (perhaps intending that 'Z' + 1 = 'A'), then rewrite your question...

Alnitak
The question is indeed incomplete - how should overflow/underflow is to be handled. Without this no complete solution can be given.
Gabi Davar
+7  A: 

You don't need to call a function to do this. Just add the number to the character directly.

For example:

'a' + 3

evaluates to

'd'
Spire
This is true for ASCII, and character sets based on it, for the A-Z letters. This covers pretty much all relevant machines in the modern world. EBCDIC would be the big exception, but it seems to be pretty much extinct.
Lars Wirzenius
You might want to rethink that comment, @liw.fi. EBCDIC is alive and well on z/OS which pretty well runs ALL the world-class banks and other financial organizations. It's even in the encapsulated UNIX run on that platform (which sometimes makes it hard to compile FOSS that depends on ASCII ordering, zLinux uses ASCII so that's better).
paxdiablo
+2  A: 

In C, a char is an integer type (like int, and long long int).

It functions just like the other integer types, except the range of values it can store is typically limited to -128 to 127, or 0 to 255, although this depends on implementation.

For example:

char x = 3;
char y = 6;
int z;

z = x + y;
printf("z = %d\n", z); //prints z = 9

The char type (usually as part of an array) is most often used to store text, where each character is encoded as a number.

Character and string constants are a convenience. If we assume the machine uses the ASCII character set (which is almost ubiquitous today), in which case capital A is encoded as 65, then:

char x = 'A';
char str[] = "AAA";

is equivalent to

char x = 65;
char str[] = {65, 65, 65, 0};

Therefore, something like 'X' + 6 makes perfect sense - what the result will be depends on the character encoding. In ASCII, it's equivalent to 88 + 6 which is 94 which is '^'.

Artelius