2016-11-10 5 views
0

特定の文字列をstringbuilderから削除する必要がありますが、何らかの理由で削除されません。これはこれまで私が持っていることです:私はパラマターとして文字列とarraylistを持つメソッドを持っています。私が渡している文字列は次のとおりです: "beabeefeab"とarraylistは、長さ2の以下の6文字の組み合わせを含んでいます:ab、ae、af、be、bf、ef。このarraylistのコンボの名前はarrayListCombosです。私はこのforループの外側にあるこのarraylistを通り、個々の文字をstringbuilderの文字列charと比較できるように、この文字列コンボの個々の文字を取得します。 inside forループはstringbuilderを通り、コンボから取得したfirstCharとmodString.charAt(x)を比較することです。たとえば、firstChar = aおよびsecondChar = bのように、最初のコンボabを見てください。私は文字列 "beabeefeab"から最初のeを削除することができますが、2つの連続したeは削除されず、次の文字列が得られます。 "babeeab"とaとbを削除した "babab"誰も助けることができる - 私は本当に感謝します。deleteCharAt()は文字列を削除しませんstringbuilder内のすべての文字列

for(int w=0;w<arrayListCombos.size();w++){ 
     String tempComboToKeep = arrayListCombos.get(w); 
     //split up char in combo and store independantly in order to compare 
     char firstChar = tempComboToKeep.charAt(0); 
     System.out.println("first char: "+firstChar); 
     char secondChar = tempComboToKeep.charAt(1); 
     System.out.println("second char: "+secondChar); 
     StringBuilder modString = new StringBuilder(s); 
     //System.out.println("here is stringbuilder before modify: "+modString.toString()); 
     //walk through stringbuilder to find the individual chars and remove rest 
     for(int x=0;x<modString.length();x++){ 
      //if first char is NOT equal to one of the combos, delete it 
      if (modString.charAt(x) != firstChar){ 
       System.out.println("char not equal to firstChar: "+modString.charAt(x)+" "+firstChar); 
       //the char inside stringbuilder does not equal either of the combo chars so need to be removed 
       if (modString.charAt(x) != secondChar){ 
        System.out.println("char not equal to secondChar either!!! " + 
          "DELETE this char from string builder: "+modString.charAt(x)); 
        modString.deleteCharAt(x); 
       } 
      } 
     } 

答えて

0

私は自分の問題を理解しました。私はstringbuilderをループして、このstringbuilderに文字を削除し、この変更されたstringbuilderをループ内で使用してすべての文字を処理しようとしていました。これを修正するには、新しい文字列ビルダを作成してappendメソッドを使用し、文字を保持する必要があるたびに追加しました。これにより、元のstringbuilderをループし続けて、文字を見逃さないようにしました。

関連する問題