字符串 charat_Java | String.charAt(index)| 从字符串中按索引获取字符
字符串 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: HCharacter at 7th index: o .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}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 ObjectString msg = null;//Scanner class ObjectScanner scan = new Scanner(System.in);//input a stringSystem.out.println("Input a string: ");msg = scan.nextLine();//printing string character by characterSystem.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
總結
以上是生活随笔為你收集整理的字符串 charat_Java | String.charAt(index)| 从字符串中按索引获取字符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星手机多少钱一个啊?
- 下一篇: 使用Java中的equals()和com