donglang8008 2015-03-28 22:54
浏览 15
已采纳

如何在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.

  • 写回答

2条回答 默认 最新

  • dongtaijue1578 2015-03-29 00:03
    关注

    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. The b character has ASCII value 98. 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿