如何读取字符串逐行并用另一个特定的字符串替换特定的行?
例如:我怎样才能逐行读取一个字符串,并用另一个特定的字符串替换特定的字符串
String myString = "This" +"\nis" + "\nonly" + "\nthe" + "\nexample";
而且我想从顶部看他们一行开始行和更换每一个这样的“这” - >>“newThis”“是” - >>“newIs”,并等等。
如何读取字符串逐行并用另一个特定的字符串替换特定的行?
例如:我怎样才能逐行读取一个字符串,并用另一个特定的字符串替换特定的字符串
String myString = "This" +"\nis" + "\nonly" + "\nthe" + "\nexample";
而且我想从顶部看他们一行开始行和更换每一个这样的“这” - >>“newThis”“是” - >>“newIs”,并等等。
可以使用split
方法:
String[] yourStringAsArray = myString.split("\n")
然后你就可以遍历您的阵列那样:
for(String s : yourStringAsArray){
s.replaceAll("oldValue", "newValue")
}
好了,你可以在 “\ n” 字符分割字符串,替换你想要的每一个元素,然后像这样将字符串重新拼接在一起:
String[] lines = myString.split("\n");
// Replace lines here
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line + "\n");
}
// Haven't dealt with the trailing "\n", but I leave that as an exercise to the user.
myString = sb.toString();
糟糕!对不起......请参阅编辑。集合和数组混合在一起。 :) –
如果你想,你可以使用以下形式将其存储为String []: String [] s_array = myString.split(“\ n”);
然后访问每个元件单独
该溶液是基于Java 8流API和lambda表达式。
public static final String DELIMITER = "\n";
public static final Pattern SPLIT_PATTERN = Pattern.compile(DELIMITER);
public static final Function<String, String> TRANSFORM_STRING = (String text) ->
SPLIT_PATTERN.splitAsStream(text)
.map(s -> "new" + s)
.collect(Collectors.joining(DELIMITER));
public static void main(String[] args) {
final String inputText = "This" + "\nis" + "\nonly" + "\nthe" + "\nexample";
final String outputText = TRANSFORM_STRING.apply(inputText);
System.out.println(outputText);
}
不清楚。您不指定应如何存储结果。至于在新行上分割源代码,正则表达式是一个解决方案。 – fge