2017-01-25 13 views
0

文字列からいくつかの文字を削除するためにループを実行しようとしています。しかし、次のコードを実行しているときは、最初の実行からのみ出力が得られます。私は文字列の残りの部分を取得しません。誰かが私がここに追加する必要があるものを助けてもらえますか?最初の反復の結果のみを表示します。ありがとう文字列ビルダーから文字を削除する

someStr = "I don't know this"; 
StringBuilder sb = new StringBuilder(someStr); 
int n = 3 
for (int i = n - 1; i < sb.length(); i = n + 1) { 
    sb = sb.deleteCharAt(i); 
} 
System.out.println(sb.toString()); 
+4

'N'とは何ですか?... –

+1

チェックはあなたの増分ステートメントは、実際に – Taelsin

+0

n個のやっていることは、任意の整数を指定できます。 2,3,4などのように – user3396478

答えて

1

for文の3番目の部分は、インデックスを増減する命令です。そこ

、それが明確であるためには、常に4

です:

1st iteration : i = 2 => you remove the 'd', your string is now "I on't know this" 

2nd iteration : i = 4 => you remove the ''', your string is now "I ont know this" 

3rd iteration : i = 4 => you remove the 't', your string is now "I on know this" 

4th iteration : i = 4 => you remove the ' ', your string is now "I onknow this" 

...

0

String.replaceAll()を使用しないのはなぜ?

someStr = "I don't know this"; 
System.out.print("Output :"); 
System.out.println(someStr .replaceAll("t", "")); 
0

文字列から文字を削除する場合は、Regexを使用することをお勧めします。これは、空のスプリング削除する必要がある文字に置き換える例です。今

public static String cleanWhitPattern(String sample, String , String regex) { 

    if (sample != null && regex != null) { 
     Pattern pattern = Pattern.compile(regex); 
     Matcher matcher = pattern.matcher(sample); 

     if (matcher.find()) { 
      return matcher.replaceAll(""); 
     } 

     return sample; 
    } 

    return null; 
} 

、あなたは単にあなたの必要なパターンで、このメソッドを呼び出します。

System.out.print(cleanWithPattern("I don't know this", "o*")); 

そして、あなたの出力はこのようになります。

I dn't knw this

関連する問題