Concatenating arrays
From CompSciWiki
Back to the Program-A-Day homepage
ProblemGiven an array of strings join the strings together to create a single string. Example Output String[] strings = { "First string is short.", "Second string is a bit longer", "Third sting is even more longererer" }; |
More with Arrays | |
---|---|---|
SolutionThere are multiple ways of joining the strings together. The simplest way, using +, you are probably already familiar with. String[] strings = { "First string is short.", "Second string is a bit longer", "Third sting is even more longererer" }; String combinedStrings = new String; for( int i = 0; i < strings.length; i++ ) { combinedStrings = combinedStrings + strings[i]; }
The String class also offer the method, concat, to concatenate strings String[] strings = { "First string is short.", "Second string is a bit longer", "Third sting is even more longererer" }; String combinedStrings = new String; for( int i = 0; i < strings.length; i++ ) { combinedStrings.concat( strings[i] ); }
Java also offers the StringBuilder class which is best used when building up larger strings String[] strings = { "First string is short.", "Second string is a bit longer", "Third sting is even more longererer" }; StringBuilder sb = new StringBuilder(); for( int i = 0; i < strings.length; i++ ) { sb.append( strings[i] ); } String combinedStrings = sb.toString(); | ||
Code |