2014-09-24 84 views
19

如何獲取字符串的第一個字符?Android如何獲取字符串的第一個字符?

string test = "StackOverflow"; 

第一個字符= 「S」

+0

看看這個教程[的charAt()](HTTP://www.tutorialspoint .com/java/java_string_charat.htm) – 2014-09-24 07:06:52

+4

可能重複[獲取字符串字符的索引-Java](http://stackoverflow.com/questions/11229986/get-string-character-by-index-java) – 2014-09-24 07:09:42

+1

我不要認爲這是無關緊要的。由於它是重複的,我投票結束。 – Keppil 2014-09-24 07:23:09

回答

51
String test = "StackOverflow"; 
char first = test.charAt(0); 
+26

或'substring(0,1)'如果你想要它作爲一個字符串而不是一個字符 – Thilo 2014-09-24 07:06:56

+0

感謝隊友,它的完美 – user1710911 2014-09-24 07:10:28

+0

這將拋出一個錯誤,如果你做'textView.setText(test.charAt(0))'作爲它是一個字符而不是字符串。 – Prabs 2017-04-28 08:15:40

40

另一種方式是

String test = "StackOverflow"; 
String s=test.substring(0,1); 

在此你有導致String

2

使用的charAt():

public class Test { 
    public static void main(String args[]) { 
     String s = "Stackoverflow"; 
     char result = s.charAt(0); 
     System.out.println(result); 
    } 
} 

這是一個tutorial

3

正如大家所說,這裏是完整的代碼片段。

public class StrDemo 
{ 
public static void main (String args[]) 
{ 
    String abc = "abc"; 

    System.out.println ("Char at offset 0 : " + abc.charAt(0)); 
    System.out.println ("Char at offset 1 : " + abc.charAt(1)); 
    System.out.println ("Char at offset 2 : " + abc.charAt(2)); 

    //Also substring method 
    System.out.println(abc.substring(1, 2)); 
    //it will print 

BC

// as starting index to end index here in this case abc is the string 
    //at 0 index-a, 1-index-b, 2- index-c 

// This line should throw a StringIndexOutOfBoundsException 
    System.out.println ("Char at offset 3 : " + abc.charAt(3)); 
} 
} 

回到這個link,讀取點4

相關問題