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

Time:06-09

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;
}

CodePudding user response:

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 = " ";
}

CodePudding user response:

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(" "));
  • Related