如何在Golang中找到下一个字符?
I'm just doing some algorithms problems out of interest in golang. I understand that in other languages to find the next character alphabetically I can bitshift the character, as a character (I'm thinking of C) is really a number.
So I tried doing
"a" >> 2
Or something to that effect, but there is a type mismatch.
I'd like to know how I can achieve this.
I am not sure where you get the idea that this gives you the 'next character'. This is not true in any language. What 'a' >> 2
does is this:
- 'a' is interpreted as
int32(97)
(example) -
>>
means 'shift X right by Y bits'. Shifting something right by 2 bits is functionally the same as an integer divide by 4. So(x >> 2) == (x / 4)
. (example) -
97 / 4 == 24
. Theb
character has ASCII value98
. So this doesn't get you anywhere near. (example)
More on the bit shifting
Bit shifting is most obvious when considering a number in its binary notation. For the expression z = x >> y
, we can note the following:
x(97): 01100001
y(2): 00000010
-------- >>
z(24): 00011000
Note that all the bits in x
have simply been moved to the right by two bits. The 1
that fell off the end is dropped.
Similarly, you can 'shift left' (<<
). Just like x >> 1
is the same as x / 2
, x << 1
is the same as x * 2
.
Expression: 5>>1 == 5/2 == 2
:
x(5): 00000101
y(1): 00000001
-------- >>
z(2): 00000010
Expression: 5<<1 == 5*2 == 10
:
x(5): 00000101
y(1): 00000001
-------- <<
z(10): 00001010
Actually getting the next character
If you want the character directly following 'a'
, you simply add 1 to it as evidenced in this example.
You're trying to shift a string, not a byte, like @Not_a_Golfer said 'a'>>2
should work fine.
However to get the next character you can do something like:
func nextChar(ch byte) byte {
if ch += 1; ch > 'z' {
return 'a'
}
return ch
}
func main() {
fmt.Println(string(nextChar('a')))
}
Of course it'd be more complex if you need more than a-z support, take a look at the unicode
package and this blog post about go strings.