2

How do i add all charAcro[] to create a string? example charAcro[0] = a, charAcro[1] = b, charAcro[2] = c, which makes the string abc

 while(resultSet.next()){
                    String Name = rs.getString(1);
                    String Acro=Name;
                    String delimiterAcro = " ";
                    String[] temp =null;
                    char[] charAcro = null;
                    temp = Name.split(delimiterAcro);
                    for(int i = 0;i<temp.length;++i){
                    charAcro[i] = temp[i].charAt(0);
                    //SOME CODE HERE?
                    }

      }

2 Answers 2

7

There is a String constructor available that takes a char array,

char data[] = {'a', 'b', 'c'};
String str = new String(data);

While I'm at it, look into Java Naming Conventions. Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Whereas variables are in mixed case with a lowercase first letter. Internal words start with capital letters.

For example in your code snippet you have,

String Name = rs.getString(1);

which is bad, if not wrong.

Moreover, you are likely to have a NullPointerException at line,

charAcro[i] = temp[i].charAt(0);

as you didn't initialise the array. Below is the code which should work for you.

String name = rs.getString(1);
String[] temp = name.split(" ");
char[] charAcro = new char[temp.length];
for (int i = 0; i < temp.length; ++i) {
    charAcro[i] = temp[i].charAt(0);
}
System.out.println(new String(charAcro));
Sign up to request clarification or add additional context in comments.

1 Comment

I answered with a StringBuilder, but this is a much more elegant solution. Kudos.
4

There's a constructor for String that accepts a char array, so just do:

String string = new String(charAcro);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.