Concatenating arrays

From CompSciWiki
Revision as of 00:12, 9 April 2010 by TimC (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Given 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

Wiki method01.jpg

Solution

There 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

Solution Code

Back to the Program-A-Day homepage