Java - 如何将字符串中的字母转换为数字? [英] Java - how to convert letters in a string to a number?

查看:2557
本文介绍了Java - 如何将字符串中的字母转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java很陌生,所以我想知道如何将字符串中的字母转换为数字,例如 hello world 将输出 8 5 12 12 15 23 15 18 12 4

所以 a = 1 b = 2 z = 26 等。

I'm quite new to Java so I am wondering how do you convert a letter in a string to a number e.g. hello world would output as 8 5 12 12 15 23 15 18 12 4.
so a=1, b=2, z=26 etc.

推荐答案

由于这很可能是一项学习任务,我会给你提示:拉丁字母字母的所有UNICODE代码点都按字母顺序排序。如果 a 的代码是某个数字 N ,则代码 b N + 1 c 的代码是 N + 2 ,依此类推; Z 的代码是 N + 26

Since this is most likely a learning assignment, I'll give you a hint: all UNICODE code points for the letters of the Latin alphabet are ordered alphabetically. If the code of a is some number N, then the code of b is N+1, the code of c is N+2, and so on; the code of Z is N+26.

您可以用减去整数的相同方式减去字符代码点。由于代码点按字母顺序排列,因此以下计算

You can subtract character code points in the same way that you subtract integers. Since the code points are alphabetized, the following calculation

char ch = 'h';
int pos = ch - 'a' + 1;

生成序列号 h ,即 8 。如果在循环中执行此计算,则会得到所需的结果。

produces the sequence number of h, i.e. 8. If you perform this calculation in a loop, you would get the result that you need.

请注意,上述公式仅适用于同一寄存器的字符。如果您的输入字符串是大小写混合,则需要在进行计算之前将每个字符转换为小写字母,否则会出错。

Note that the above formula works only with characters of the same register. If your input string is in mixed case, you need to convert each character to lower case before doing the calculation, otherwise it would come out wrong.

这篇关于Java - 如何将字符串中的字母转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆