I have a multiple line string that is taken as a user input. I broke the string into ArrayList
by str.split("\\\\s ")
and changed a particular word if it occurred, now i want to merge the words in the ArrayList
with the replaced word in it and form the string again in a multiple line pattern only. I'm not getting how to do this. Please help.
Using only standard Java (assuming your ArrayList is called words
)
StringBuilder sb = new StringBuilder();
for (String current : words)
sb.append(current).append(" ");
String s = sb.toString().trim();
If you have the Guava library you can use Joiner:
String s = Joiner.on(" ").join(words)
Both of these will work even if the type of words
is String[]
.
If you want to preserve the line structure, I suggest the following approach: first break the input string into lines by using .split("\\n")
. Then, split each lines to words using .split("\\\\s")
. Here's how the code should look like:
public String convert(String input, String wordToReplace, String replacement) {
StringBuilder result = new StringBuilder();
String[] lines = input.split("\n");
for (String line : lines) {
boolean isFirst = true;
for (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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.