【问题标题】:How to remove the last character from a multiline string?如何从多行字符串中删除最后一个字符?
【发布时间】:2019-01-22 08:47:13
【问题描述】:

示例: 考虑如下字符串:

String a="This line1 has a,b,c,\nThis line2 has d,e,f, \nThis line3 has g,h,i";
System.out.println(a);

输出:

This line1 has a,b,c,                 
This line2 has d,e,f,                        
This line3 has g,h,i

由于这是一个多行字符串,我如何才能从输出中删除每行最后出现的逗号并打印如下所述的输出?

This line1 has a,b,c                
This line2 has d,e,f                        
This line3 has g,h,i

【问题讨论】:

  • Arrays.stream(a.split("\n")) .map(l -> l.replaceAll("(.*?),\\s*$", "$1")) .forEach(System.out::println);
  • 到目前为止你有什么尝试?

标签: java string multilinestring


【解决方案1】:

你可以使用正则表达式:

String output = a.replaceAll(",\\s*\n", "\n");

它将用一个换行符替换任何逗号、0 个或多个空格和换行符的序列。

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2011-11-18
    • 2017-08-19
    • 2016-04-16
    • 2020-03-12
    • 2011-01-19
    相关资源
    最近更新 更多