0

String からコメント (/* */) の文字を削除しようとしていますが、特に 2 番目のコメントからそれらを抽出する方法がわかりません。これは私のコードです:

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.

ご覧のとおり、コメントは削除できませんが、最初のコメントは削除できません。

4

2 に答える 2

0

両方の文字列のインデックスを取得したら、それを StringBuilder に変換し、メソッド deleteCharAt(int index) を使用します。

于 2021-03-20T04:39:32.937 に答える
0

それはワンライナーです:

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

これは、ゼロを含む任意の数のコメントに対応します。

于 2021-03-20T04:39:57.813 に答える