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?

+3


source to share


3 answers


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:

+4


source


What you have to do is

String c = s.substring(0, 2);

      



Now why is your code not working? Since you are adding two values char

and integer addition is used for that. Thus, the result is an integer that cannot be assigned to a String variable.

+1


source


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

      

0


source







All Articles