Strip Comments

问题

输入多行字符串,要求删除所有行中的注释,并且输出行尾不可有空格。

例子

输入
apples, pears # and bananas
grapes
bananas !apples

输出
apples, pears
grapes
bananas

我的代码

package codewars;

import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StripComments {
    public static String stripComments(String text, String[] commentSymbols) {
        return Stream.of(text.split("\n")).map(e -> {
            for (String commentSymbol : commentSymbols) {
            //删除注释
                e = e.indexOf(commentSymbol) >= 0? e.substring(0, e.indexOf(commentSymbol)) : e;
            }
            //删除行尾的空格
            return e.replaceAll("\\s$", "");
        }).collect(Collectors.joining("\n"));
    }

    public static void main(String[] args) {
        System.out.println(StripComments.stripComments("-", new String[] {"-"}));

    }
}

高手的代码

import java.util.Arrays;
import java.util.stream.Collectors;

public class StripComments {

  public static String stripComments(String text, String[] commentSymbols) {
    String pattern = String.format(
        "[ ]*([%s].*)?$",
        Arrays.stream( commentSymbols ).collect( Collectors.joining() )
    );
    return Arrays.stream( text.split( "\n" ) )
        .map( x -> x.replaceAll( pattern, "" ) )
        .collect( Collectors.joining( "\n" ) );
  }

}

分析

高手的代码值得学习的地方是,用一个正则表达式去除注释,比较之下我的代码用了一个for循环,还需要定位注释符号的位置,这样消耗就比较大了,看来巧妙的运用正则表达式能够减少很多工作量

猜你喜欢

转载自blog.csdn.net/qqqq0199181/article/details/80820037
今日推荐