字符串 charat
String.charAt() function is a library function of String class, it is used to get/retrieve the specific character from a string. Where, the index starts from 0 and ends to String.lenght-1.
String.charAt()函数是String类的库函数,用于从字符串中获取/检索特定字符。 其中,索引从0开始,到String.lenght-1结束。
For example, if there is string "Hello", its index will starts from 0 and end to 4.
例如,如果存在字符串“ Hello” ,则其索引将从0开始到4结束。
Note: If you try to access the character out of bounds, an exception StringIndexOutOfBoundsException will generate. So, be careful while using index in the string.
注意:如果您尝试超出范围访问字符,则会生成异常StringIndexOutOfBoundsException 。 因此,在字符串中使用索引时要小心。
Example1:
范例1:
In this example, there is string initialized by "Hello world!" and we have to access its 0th and 7th character.
在此示例中,存在由“ Hello world!”初始化的字符串。 并且我们必须访问其第 0和第 7 个字符。
public class Example1
{
public static void main (String[] args) throws java.lang.Exception
{
String msg = "Hello world!";
System.out.println("Character at 0th index: "+ msg.charAt(0));
System.out.println("Character at 7th index: " + msg.charAt(7));
}
}
Output
输出量
Character at 0th index: H
Character at 7th index: o
Example2:
范例2:
In this example, we have to read a string and print it character by character
在此示例中,我们必须读取字符串并逐个字符打印
import java.util.*;
public class Example2
{
public static void main (String[] args) throws java.lang.Exception
{
//string Object
String msg = null;
//Scanner class Object
Scanner scan = new Scanner(System.in);
//input a string
System.out.println("Input a string: ");
msg = scan.nextLine();
//printing string character by character
System.out.println("Input string is: ");
for(int loop =0; loop<msg.length(); loop++)
System.out.print(msg.charAt(loop));
}
}
Output
输出量
Input a string: I love programming.
Input string is:
I love programming.
翻译自: https://www.includehelp.com/java/String-charAt-function-to-get-character-by-Index-from-string.aspx
字符串 charat