我正在尝试从 String 中删除 comments(/* */) 的字符,但我不确定如何提取它们,尤其是从第二条评论中提取它们。这是我的代码:
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;
}
在测试人员类中:
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."));
输出:The hippo is/* a reclusive*/ /*and *//*nocturnal animal */native to Western Africa. // expected: The hippo is native to Western Africa.
如您所见,除了第一个评论,我无法删除评论。