java - Converting arraylist to string -


i have multiple line string taken user input. broke string arraylist str.split("\\s ") , changed particular word if occurred, want merge words in arraylist replaced word in , form string again in multiple line pattern only. i'm not getting how this. please help.

using standard java (assuming arraylist called words)

stringbuilder sb = new stringbuilder(); (string current : words)    sb.append(current).append(" "); string s = sb.tostring().trim(); 

if have guava library can use joiner:

string s = joiner.on(" ").join(words) 

both of these work if type of words string[].

if want preserve line structure, suggest following approach: first break input string lines using .split("\n"). then, split each lines words using .split("\\s"). here's how code should like:

public string convert(string input, string wordtoreplace, string replacement) {   stringbuilder result = new stringbuilder();   string[] lines = input.split("\n");   (string line : lines) {     boolean isfirst = true;     (string current : line.split("\\s")) {       if (!isfirst)         result.append(" ");       isfirst = false;       if (current.equals(wordtoreplace))         current = replacement;       result.append(current);     }     result.append("\n");   }    return result.tostring().trim(); } 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -