2

私はこのJavaコードを持っています

    String s3="10100111001";
    String s4="1001";
    String s5="0";
    System.out.println(s3);
    int last_index=3; //To replace only the last 

    while(last_index>=0) {
        last_index=s3.indexOf(s4,last_index);
        System.out.println("B:" +last_index);
        if(last_index>=0)
        {

            s3=s3.replace(s3.substring(last_index,(last_index+s4.length())),s5);
            last_index=last_index+s4.length();
            System.out.println("L:"+last_index);
            continue;
        }

        else
        {
            continue;
        }

    }
    System.out.println(s3);

理想的には、このコードは最後の発生のみを置換する必要があり1001ますが、両方の発生を置換します1001

私の出力はです10010が、そうあるべきです10100110。どこが間違っているのですか?

4

1 に答える 1

0

The expression

s3.substring(last_index,(last_index+s4.length()))

returns "1001" string. Calling replace with that string as the argument will perform the replacement throughout the entire string, so it would replace both occurrences.

To fix your solution, you can replace the call of replace with a composition of three substrings:

  • from zero to last_index
  • s5
  • from last_index+4 to the end.

Like this:

s3=s3.substring(0, last_index) + s5 + s3.substring(last_index+s4.length());
于 2013-06-29T00:47:16.080 に答える