Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append char arrays to create string

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?
                    }

      }
like image 578
JLawrence Avatar asked Jul 04 '26 12:07

JLawrence


1 Answers

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));
like image 148
mkoryak Avatar answered Jul 06 '26 01:07

mkoryak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!