[英]How do I remove characters between /* and */ from a string
我正在嘗試從 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;
}
在測試儀 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.
如您所見,除了第一個評論,我無法刪除評論。
獲取兩個字符串的索引后,將其轉換為 StringBuilder 並使用方法 deleteCharAt(int index)。
這是一個單行:
public String removeComments(String s) {
return s.replaceAll("/\\*.*?\\*/", "");
}
這迎合了任何數量的評論,包括零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.