无法删除空格

时间:2018-04-01 17:15:43

标签: java regex

我知道不应该被问到,但我对卡塔有问题,我认为我已经做好了一切。

我一直试图自己修复它,但是在一个问题上已经有一段时间了,但仍然没有。

这是卡塔:

  

完成解决方案,以便删除传入的任何一组注释标记后面的所有文本。行末尾的任何空格也应该被删除。

     

给定输入字符串:

apples, pears # and bananas 
grapes  
bananas !apples 
  

预期产量   将是:

apples, pears 
grapes  
bananas

这是我的代码:

public class StripComments {

    public static String stripComments(String text, String[] commentSymbols) {
        String[] text2 = text.split("\n");
        String result = "";

        int symbolIndex = -1;
        for (int i = 0; i < text2.length; i++) {
            for (int j = 0; j < commentSymbols.length; j++) {

                symbolIndex = text2[i].indexOf(commentSymbols[j]);
                if (symbolIndex >= 0) {
                    text2[i] = (text2[i].substring(0, symbolIndex)).replaceAll(" +$", "");
                }

            }

        }

        result = String.join("\n", text2);

        return result.replaceAll(" +$", "");


    }
}

问题是,我无法通过尝试测试

>  edges(StripCommentsTest)
expected:<a[
 b]
c> but was:<a[ 
 b ]
c>

我不知道为什么。 b之后的空格总是在那里,如果我试图改变某些东西,它会在c之后移动。

我想我已经尝试了一切。修剪(),正则表达式,似乎没什么用。

你可以给我一些提示吗?

可以查看的测试:

public void stripComments() throws Exception {
        assertEquals(
                "apples, pears\ngrapes\nbananas",
                StripComments.stripComments( "apples, pears # and bananas\ngrapes\nbananas !apples", new String[] { "#", "!" } )
        );

        assertEquals(
                "a\nc\nd",
                StripComments.stripComments( "a #b\nc\nd $e f g", new String[] { "#", "$" } )
        );

1 个答案:

答案 0 :(得分:2)

啊!我终于找到了你的错误。

如果没有评论,您的代码不会删除尾随空格

这是一个测试用例:

c

如您所见,输入的第二行有一个尾随空格 - public static String stripComments(String text, String[] commentSymbols) { String[] lines = text.split("\n"); // escape the comment symbols so that they can be used as regex List<String> escapedCommentSymbols = Arrays.stream(commentSymbols).map(Pattern::quote).collect(Collectors.toList()); for(int i = 0 ; i < lines.length ; i++) { // create a regex that matches the comment portion of a line String regex = "(" + String.join("|", escapedCommentSymbols) + ").+$"; lines[i] = lines[i].replaceAll(regex, ""); // replace trailing whitespace even if it is not a comment. lines[i] = lines[i].replaceAll("\\s+$", ""); } return String.join("\n", (CharSequence[]) lines); } 后跟一个空格。你的解决方案不会删除它,但kata要求你(虽然我同意它有点不清楚“何时”删除尾随空格)。尝试编辑解决方案以删除尾随空格,即使该行没有注释。

无论如何,这是我的解决方案:

awesome_print