通过索引获取字符串字符 - 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数据类型,而是字符串中的字母或数字。这里重要的是我在调用方法时没有收到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 a_char = text.charAt(0);
System.out.println(a_char); // Prints f
有关详细信息,请参阅 上的Java文档String.charAt
。如果您想要另一个简单的教程,请这个或这一个。
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 a_letter = Character.toString(text.charAt(0));
System.out.println( a_letter ); // Prints f
如果您想了解有关字符的更多信息
class和 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屋!