Search code examples
javanewlinestringbuilder

Testing String results which both contain \n


So I am quickly losing my mind trying to answer a question on codewars. The aim of the code challenge is to strip a string down removing all comments from the code.

So I have this code, which does the stripping and gives me the results I'd expect:

   public static String stripComments(String text, String[] commentSymbols) {

        boolean ignoreNext = false;
        StringBuilder noCommentString = new StringBuilder();
        StringBuilder currentLine = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (String.valueOf(c).equals("\n")) {
                currentLine.append("\\n");
                ignoreNext = false;
                noCommentString.append(currentLine.toString().trim());
                currentLine = new StringBuilder();
                continue;
            }
            if (!ignoreNext) {

                for (int j = 0; j < commentSymbols.length; j++) {
                    if (commentSymbols[j].equals(String.valueOf(c))) {
                        ignoreNext = true;
                        noCommentString.append(currentLine.toString().trim());
                        currentLine = new StringBuilder();
                    }
                }
                if (!ignoreNext) {
                    currentLine.append(c);
                }
            }
        }
        return noCommentString.toString();
    }

But for some rather strange reason, this test fails:

   @Test
    public void stripComments() throws Exception {

        String expected = "apples, pears\ngrapes\nbananas";
        String actual =  StripComments.stripComments("apples, pears # and bananas\ngrapes\nbananas !apples", new String[]{"#", "!"});
        assertEquals(expected, actual);
    }

If I am to evaluate the code the actual String is:

apples, pears\ngrapes\nbananas

and of course you can see the expected String is:

apples, pears\ngrapes\nbananas

why on earth is this failing, I'm certain it's something to do with some bizarre \n behaviour


Solution

  • I think you should append "\n" rather than "\\n". It doesn't require escape character here. Also currentLine.toString().trim(), causes to delete the new line character so avoid it. Rather try using currentLine.toString(). Some system might require to use "\r\n" rather than "\n". Try this if "\n" doesn't work for you.