[英]Converting arraylist to string
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. 我通过
str.split("\\\\s ")
将字符串分解为ArrayList
,并更改了一个特定的单词(如果它发生了),现在我想将ArrayList
中的单词与其中的替换单词合并,并以倍数形式再次形成字符串仅线条图案。 I'm not getting how to do this. 我没有得到如何做到这一点。 Please help.
请帮忙。
Using only standard Java (assuming your ArrayList is called words
) 仅使用标准Java(假设ArrayList称为
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: 如果您拥有Guava库,则可以使用Joiner:
String s = Joiner.on(" ").join(words)
Both of these will work even if the type of words
is String[]
. 即使
words
的类型为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")
. 如果要保留行结构,建议采用以下方法:首先使用
.split("\\n")
将输入字符串分成几行。 Then, split each lines to words using .split("\\\\s")
. 然后,使用
.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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.