3

コンソール (下の画像) があり、すべての oldstinrg を newstring に置き換えるコマンドがあります。しかし、それらのうちの何個が置き換えられたかをどのように数えますか?

(コードが a から b を 1 回だけ置き換えた場合、値は 1 になりますが、a から b を 2 回置き換えた場合、値は 2 になります)

(これはコードの一部にすぎませんが、他の部分は不要であり、コードのこの部分にどのように関連していてもかまいません)

else if(intext.startsWith("replace ")){


                String[] replist = original.split(" +");    

                String repfrom = replist[1];
                String repto = replist[2];

                lastorep = repfrom;
                lasttorep = repto;

                String outtext = output.getText();
                String newtext = outtext.replace(repfrom, repto);
                output.setText(newtext);

                int totalreplaced = 0; //how to get how many replaced strings were there?

                message("Total replaced: " + totalreplaced + " from " + repfrom + " to " + repto);

            }

私のコンソール画像

4

2 に答える 2

6

String.replaceFirst を使用して、自分で数えることができます。

String outtext = output.getText();
String newtext = outtext;
int totalreplaced = 0;

//check if there is anything to replace
while( !newtext.replaceFirst(repfrom, repto).equals(newtext) ) {
    newtext = newtext.replaceFirst(repfrom, repto);
    totalreplaced++;
}

message("Total replaced: " + totalreplaced + " from " + repfrom + " to " + repto);
于 2013-06-20T16:19:13.723 に答える
5

現在受け入れられている回答にはほとんど問題がありません。

  1. 呼び出すたびに文字列の先頭から繰り返す必要があるreplaceFirstため、あまり効率的ではありません。
  2. しかし、もっと重要なことは、「予期しない」結果を返す可能性があることです。たとえば、 に置き換えたい場合は"ab""a"文字列"abb"メソッドではなく、一致1する結果として返され2ます。次の理由で発生します。

    • 最初の反復"abb""ab"
    • "ab"再び一致する可能性があり、これは再び一致して置き換えられます。

    つまり、置換後"ab"->"b" "abb"は に進化"a"ます。


これらの問題を解決し、1 回の繰り返しで置換数を取得するには、次のような方法を使用Matcher#appendReplacementできMatcher#appendTailます

String outtext = "Some text with word text and that will need to be " +
        "replaced with another text x";
String repfrom = "text";
String repto = "[replaced word]";

Pattern p = Pattern.compile(repfrom, Pattern.LITERAL);
Matcher m = p.matcher(outtext);

int counter = 0;
StringBuffer sb = new StringBuffer();
while (m.find()) {
    counter++;
    m.appendReplacement(sb, repto);
}
m.appendTail(sb);

String newtext = sb.toString();

System.out.println(newtext);
System.out.println(counter);
于 2013-06-20T16:45:55.100 に答える