简体   繁体   中英

How do I remove characters between /* and */ from a string

I am trying to remove characters of comments(/* */) from the String s, but I am not sure how I extract them, especially, from the second comment. This is my code:

public String removeComments(String s)
{
    String result = "";
    int slashFront = s.indexOf("/*");
    int slashBack = s.indexOf("*/");
    
    if (slashFront < 0) // if the string has no comment
    {
        return s;
    }
    // extract comment
    String comment = s.substring(slashFront, slashBack + 2);
    result = s.replace(comment, "");
    return result;
    }

In tester class:

System.out.println("The hippo is native to Western Africa. = " + tester.removeComments("The /*pygmy */hippo is/* a reclusive*/ /*and *//*nocturnal animal */native to Western Africa."));

output: The hippo is/* a reclusive*/ /*and *//*nocturnal animal */native to Western Africa. // expected: The hippo is native to Western Africa. The hippo is/* a reclusive*/ /*and *//*nocturnal animal */native to Western Africa. // expected: The hippo is native to Western Africa.

As you can see, I can not remove comments but the first one.

After getting the index of both String, convert it to a StringBuilder and use method deleteCharAt(int index).

It's a one-liner:

public String removeComments(String s) {
    return s.replaceAll("/\\*.*?\\*/", "");
}

This caters for any number of comments, including zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM