Clone
Clone

Reputation: 3658

Is there a way of alter first iteration of for loop for adding strings?

I currently have a for loop, and I am looking for a quick and elegant method to remove the plus sign + from the first "adding" of the loop, so the results is not +example+input+string but rather example+input+string preferably without the need of rewriting the loop much.

String inpputString = "example input string";
String outputString= "";
    
String[] stringPieces= mainString.split(" ");
    
for (String strTemp : stringPieces){
    outputString = outputString + "+" + strTemp;
}

Upvotes: 0

Views: 104

Answers (2)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29028

Personally, I would proffer the solution using String.join() proposed by @shmosel in the comment.

Here is another way of achieving this with Stream API:

String outputString = 
    Arrays.stream(stringPieces).collect(Collectors.joining("+"));

Upvotes: 0

dangling else
dangling else

Reputation: 448

Based on the observation that you don't want a separator the first time - use an empty separator the first time!

String sep = "";
for (String strTemp : stringPieces) {
    outputString += sep + strTemp;
    sep = "+";
}

Upvotes: 2

Related Questions