我有一个Unicode字符列表,需要用其他一些字符替换后才能正常工作。但是,我必须循环两次才能获得 结果。可以只循环一次并得到结果吗?
例如,我想将此“ \ u201C”,“ \ u201D”替换为“ \””(带标准双引号的智能双引号) 并将“ \ u2018”,“ \ u2019”替换为“'”(智能单引号和标准单引号)
public class HelloWorld{
public static void main(String []args){
List<String> toRemove = Arrays.asList("\u201C","\u201D");
List<String> toRemove1 = Arrays.asList("\u2018","\u2019");
String text = "KURT’X45T”YUZXC";
text=toRemove.stream()
.map(toRem -> (Function<String,String>) s -> s.replaceAll(toRem, "\""))
.reduce(Function.identity(), Function::andThen)
.apply(text);
System.out.println("---text--- "+ text);
text=toRemove1.stream()
.map(toRem -> (Function<String,String>) s -> s.replaceAll(toRem, "'"))
.reduce(Function.identity(), Function::andThen)
.apply(text);
System.out.println("---text-1-- "+ text);
}
}
答案 0 :(得分:2)
public class HelloWorld{
public static void main(String []args){
Map<String,String> map = new HashMap<String,String>();
map.put("\u2018","'");
map.put("\u2019","'");
map.put("\u201C","\"");
map.put("\u201D","\"");
List<String> toRemove = Arrays.asList("\u2018","\u2019","\u201C","\u201D");
String text = "KURT’X45T”YUZXC";
text=map.entrySet().stream()
.map(e -> (Function<String,String>) s -> s.replaceAll(e.getKey(), e.getValue()))
.reduce(Function.identity(), Function::andThen)
.apply(text);
System.out.println(text);
// or you can even do like this
text=map.entrySet().stream()
.map(e -> (Function<String,String>) s -> s.replaceAll(e.getKey(), e.getValue()))
.reduce(Function.identity(),(a, b) -> a.andThen(b))
.apply(text);
System.out.println(text);
}
}