Concatenate the first two characters of a string
I have String s = "abcd"
, and I want to make a separate one String c
, which is, say, the first two characters String s
. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But it does error: incompatible types
. What should I do?
You have to concatenate the two strings, not char
s. See String#charAt
, it returns char
. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See JLS - 5.6.2. Binary numeric promotion .
You should:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
Once you understand your problem, the following is the best solution:
String c = s.substring(0,2)
Additional Information:
- ASCII table
- Worth knowing -
StringBuilder
-
String#substring
source to share
String s = "abcd";
First two characters of string s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);
source to share