问题
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?
回答1:
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'
回答2:
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...
回答3:
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 '^'.
来源:https://stackoverflow.com/questions/763172/char-shifting-in-c