如何逐行读取String并将特定行替换为另一个特定的字符串?
例如:
String myString = "This" +"\nis" + "\nonly" + "\nthe" + "\nexample";
我想从顶部开始逐行读取它们并替换每一个这样的"这个" - >> " newThis" "是" - >> " newIs"等等。
答案 0 :(得分:1)
您可以使用split
方法:
String[] yourStringAsArray = myString.split("\n")
然后你可以像这样迭代你的数组:
for(String s : yourStringAsArray){
s.replaceAll("oldValue", "newValue")
}
答案 1 :(得分:1)
好吧,你可以在“\ 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();
答案 2 :(得分:0)
如果需要,可以使用以下命令将其存储为String []: String [] s_array = myString.split(" \ n");
然后单独访问每个元素
答案 3 :(得分:0)
此解决方案基于Java 8 Stream API和lambdas。
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);
}