-5

I have big string array and on every index I have a letter. I need to make a recall from this array and compose all this letters to one word/string. How would I do that in java?

String[] letters;
int lettersToRecall =16;
String word;
for(int i=0; i<lettersToRecall; i++){
//accumm letters into String Word..
}
Kara
  • 6,115
  • 16
  • 50
  • 57
menemenemu
  • 209
  • 1
  • 2
  • 8

4 Answers4

3

This most straightforward method is to add all strings together:

String word = "";
for(int i = 0; i < lettersToRecall; i++){
    word += letters[i];
}

This method (simply adding String objects) wastes lots of String instances as each addition result in a new instance.

So, if you are concerned with resource usage you could use StringBuilder instead:

StringBuilder builder = new StringBuilder();
for(int i = 0; i < lettersToRecall; i++){
    builder.append(letters[i]);
}
String word = builder.toString();

For more information check when to use StringBuilder in java

Community
  • 1
  • 1
Veger
  • 37,240
  • 11
  • 105
  • 116
1
String letters="your string here";
String result="";
for(int i=0;i<letters.length();i++)
{
    if((letters.charAt(i)>=65&&letters.charAt(i)<=90)||(letters.charAt(i)>=97&&letters.charAt(i)<=122))
    result+=letters.charAt(i);

}
System.out.println("result"+result);
avinash
  • 163
  • 2
  • 12
  • Uhm... the OP has a `String` *array* for the letters and the question is how to convert it into a `String`. Not how to copy one ~String` to another... – Veger Jan 24 '13 at 10:53
0
 public class Main {

    public static void main(String[] args) {
        String[] letters = new String[3];
        letters[0] = "a";
        letters[1] = "b";
        letters[2] = "c";
        StringBuilder word = new StringBuilder();
        for (int i = 0; i < letters.length; i++) {
            word.append(letters[i]);
        }
        System.out.println(word);        
    }
}

I found another way of doing it, How about just this?

System.out.println(Arrays.toString(letters).replaceAll(",|\\s|\\]$|^\\[", ""));

Please note, only use when you don't have space or , in your string

Avinash Nair
  • 1,984
  • 2
  • 13
  • 17
0

You can use Commons-lang.jar to complete this task.The sample code:

word = StringUtils.join(letters);

If you want to write it by yourself.Try below:

public String join(String[] letters){
    StringBuffer buffer = new StringBuffer();
    for(int idx=0;idx <letters.length;idx++){
        buffer.append(letters[idx]);
    }
    return buffer.toString();
}
William Feirie
  • 624
  • 3
  • 7
  • I don't think he needs a synchronized Class, so StringBuilder should suffice. But it's a good thing to mention, if explained. – keyser Jan 24 '13 at 10:33