Wrap around chars in a string

Given a "char s[]" I want to shift every char of it "offset" positions. For example, given offset = 1 (shift 1 position), 'a' should become 'b', 'i' becomes 'j'. For 'z', however, it should wrap around and become 'a'.
1
2
3
4
5
6
7
void (char s[], int offset) {
   int i = 0;
   while (s[i]) {
      s[i] = 'a' + (s[i]+offset)%('z'-'a'+1);
      ++i;
   }
}


However, on my machine, I got correct result with:
 
s[i] = 'a' + (s[i]+offset+7)%('z'-'a'+1);


Is this kind of conversion machine-dependent or did I do sth. wrong? If it is the former, what would be a generic solution? Thanks in advance.

Please NOTE that the chars in s[] are composed of low-case letters from 'a' to 'z' inclusive.

Last edited on
This is not right at all. Try it with offset 0 and s[i] = 'a'.
s[i] = 'a' + ('a')%24 = 'a' + 17 = 'r' //I think..
what you need is
s[i] = 'a' + (s[i]-'a'+offset)%('z'-'a'+1);
what +7 did was move 'a' to a value that is a multiple of 24. That should work on all machines, unless someone doesn't use ASCII.. Still, you should try to avoid using magic numbers like that.
Topic archived. No new replies allowed.