Difference between revisions of "Concatenating arrays"
From CompSciWiki
m (Fixed photo) |
|||
Line 11: | Line 11: | ||
|SideSectionTitle=More with Arrays | |SideSectionTitle=More with Arrays | ||
|SideSection= | |SideSection= | ||
− | [[Image:Wiki_method01.jpg| | + | [[Image:Wiki_method01.jpg|center]] |
Revision as of 00:12, 9 April 2010
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 |