Search code examples
javastringcomments

Java: Removing comments from string


I'd like to do a function which gets a string and in case it has inline comments it removes it. I know it sounds pretty simple but i wanna make sure im doing this right, for example:

private String filterString(String code) {
  // lets say code = "some code //comment inside"

  // return the string "some code" (without the comment)
}

I thought about 2 ways: feel free to advice otherwise

  1. Iterating the string and finding double inline brackets and using substring method.
  2. regex way.. (im not so sure bout it)

can u tell me what's the best way and show me how it should be done? (please don't advice too advanced solutions)

edited: can this be done somehow with Scanner object? (im using this object anyway)


Solution

  • To find the substring before a constant substring using a regular expression replacement is a bit much.

    You can do it using indexOf() to check for the position of the comment start and substring() to get the first part, something like:

    String code = "some code // comment";
    int    offset = code.indexOf("//");
    
    if (-1 != offset) {
        code = code.substring(0, offset);
    }