简体   繁体   English

如何从字符串中删除 /* 和 */ 之间的字符

[英]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.我正在尝试从 String 中删除 comments(/* */) 的字符,但我不确定如何提取它们,尤其是从第二条评论中提取它们。 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:在测试仪 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. 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).获取两个字符串的索引后,将其转换为 StringBuilder 并使用方法 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.这迎合了任何数量的评论,包括零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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