37

How to get first character of string?

string test = "StackOverflow";

first character = "S"

Suragch
  • 428,106
  • 278
  • 1,284
  • 1,317
user1710911
  • 629
  • 3
  • 7
  • 14

4 Answers4

87
String test = "StackOverflow"; 
char first = test.charAt(0);
Maveňツ
  • 9,147
  • 14
  • 53
  • 94
Karakuri
  • 37,627
  • 12
  • 79
  • 103
68

Another way is

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

In this you got result in String

M D
  • 47,398
  • 9
  • 92
  • 112
5

You can refer this link, point 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 

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) );
 }
}
ajitksharma
  • 4,366
  • 2
  • 20
  • 38
4

Use charAt():

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

Here is a tutorial

Sagar Pilkhwal
  • 5,914
  • 2
  • 27
  • 78