按索引获取字符串字符 - Java [英] Get string character by index - Java
问题描述
我知道如何计算字符串中某个字符或数字的索引,但是有没有什么预定义的方法可以用来给我在 nth 位置的字符?因此,在字符串foo"中,如果我要求索引为 0 的字符,它将返回f".
I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the nth position? So in the string "foo", if I asked for the character with index 0 it would return "f".
注意 - 在上面的问题中,字符"不是指 char 数据类型,而是指字符串中的字母或数字.这里重要的是,调用该方法时我没有收到一个字符,而是一个字符串(长度为 1).我知道 substring() 方法,但我想知道是否有更简洁的方法.
Note - in the above question, by "character" I don't mean the char data type, but a letter or number in a string. The important thing here is that I don't receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.
推荐答案
您正在寻找的方法是 charAt
.举个例子:
The method you're looking for is charAt
. Here's an example:
String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
有关更多信息,请参阅关于 String.charAt
的 Java 文档.如果你想要另一个简单的教程,这个或这个.
For more information, see the Java documentation on String.charAt
. If you want another simple tutorial, this one or this one.
如果您不想将结果作为 char
数据类型,而是作为字符串,您可以使用 Character.toString
方法:
If you don't want the result as a char
data type, but rather as a string, you would use the Character.toString
method:
String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
如果您想了解有关 Character
类和 toString
方法的更多信息,我从 有关 Character.toString 的文档.
If you want more information on the Character
class and the toString
method, I pulled my info from the documentation on Character.toString.
这篇关于按索引获取字符串字符 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!