Android如何获取字符串的第一个字符?

use*_*911 30 java string

如何获得字符串的第一个字符?

string test = "StackOverflow";
Run Code Online (Sandbox Code Playgroud)

第一个字符="S"

Kar*_*uri 71

String test = "StackOverflow"; 
char first = test.charAt(0);
Run Code Online (Sandbox Code Playgroud)

  • 或者`substring(0,1)`如果你想把它当作一个String而不是一个字符 (39认同)
  • 如果您执行“textView.setText(test.charAt(0))”,则会抛出错误,因为它是字符而不是字符串。 (2认同)

M D*_*M D 56

另一种方式是

String test = "StackOverflow";
String s=test.substring(0,1);
Run Code Online (Sandbox Code Playgroud)

在这,你得到了结果 String


aji*_*rma 5

您可以参考此链接,第 4 点。

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 
Run Code Online (Sandbox Code Playgroud)

公元前

// 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) );
 }
}
Run Code Online (Sandbox Code Playgroud)