我可以在Java中使用charAt吗?
当我尝试乘以charAt时,我收到了“大号”:
String s = "25999993654"; System.out.println(s.charAt(0)+s.charAt(1));
结果:103
但是当我想只收到一个号码时就可以了。
在JAVA文档中:
the character at the specified index of this string. The first character is at index 0.
所以我需要解释或解决方案(我认为我应该将字符串转换为int,但在我看来这是不必要的工作)
char
是一个完整的类型 。 示例中s.charAt(0)
的值是数字50的char
版本( '2'
的字符代码)。 s.charAt(1)
是(char)53
。 当你对它们使用+
时,它们会转换为整数,最终会得到103(而不是100)。
如果您尝试使用数字 2
和5
,是的,您将需要解析它们。 或者如果您知道它们是标准的ASCII样式数字(字符代码48到57,包括在内),您可以从它们中减去48(因为48是'0'
的字符代码)。 或者更好的是,正如Peter Lawrey在其他地方指出的那样,使用Character.getNumericValue
,它可以处理更广泛的字符。
是 – 您应该解析提取的数字或使用ASCII图表function并减去48:
public final class Test { public static void main(String[] a) { String s = "25999993654"; System.out.println(intAt(s, 0) + intAt(s, 1)); } public static int intAt(String s, int index) { return Integer.parseInt(""+s.charAt(index)); //or //return (int) s.charAt(index) - 48; } }