2014-09-24 86 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

相关问题