2014-09-24 7 views
19

Come ottenere il primo carattere di stringa?Android Come ottenere il primo carattere di stringa?

string test = "StackOverflow"; 

primo carattere = "S"

+0

un'occhiata a questo tutorial [charAt()] (http: //www.tutorialspoint .com/java/java_string_charat.htm) –

+4

possibile duplicato di [Ottieni carattere stringa per indice - Java] (http://stackoverflow.com/questions/11229986/get-string-character-by-index-java) –

+1

I non pensare che questo sia fuori tema. Ho votato per chiudere perché si tratta di un duplicato. – Keppil

risposta

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

o 'sottostringa (0,1)' se lo si vuole come stringa invece di un carattere – Thilo

+0

Grazie amico, è perfetto – user1710911

+0

questo genererà un errore se si esegue 'textView.setText (test.charAt (0))' come è un char non stringa. – Prabs

40

Un altro modo è

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

In questo sei stato tradurrà in String

2

Usa charAt():

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

Ecco un tutorial

3

Come accennato da tutti, qui è completa frammento di codice.

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)); 
} 
} 

Vai a questa link, leggere punto 4.

Problemi correlati