2017-03-03 8 views
1

文字列内の他の文字を維持しながら、指定した文字列内の1文字を置き換える必要があります。文字列内の1文字を置換する

コードは次のとおりです。

if(command.equalsIgnoreCase("replace single")) 
    { 
     System.out.println("Enter the character to replace"); 
     String char2replace = keyboard.nextLine(); 
     System.out.println("Enter the new character"); 
     String secondChar = keyboard.nextLine();  
     System.out.println("Which " + char2replace + " would you like to replace?"); 
     int num2replace = keyboard.nextInt(); 

      for(int i=0; i< bLength; i++) 
      { 

       if(baseString.charAt(i)== char2replace.charAt(0)) 
       { 
        baseString = baseString.substring(0, i) + 
          secondChar + baseString.substring(i + 1); 

       } 

答えて

1

あなたはほとんどそれは、ちょうどあなたのループ内でカウンタを追加しました:

int num2replace = keyboard.nextInt(); 
int count = 0; 
for (int i = 0; i < bLength; i++) { 
    if (baseString.charAt(i) == char2replace.charAt(0)) { 
     count++; 
     if (count == num2replace){ 
      baseString = baseString.substring(0, i) + 
        secondChar + baseString.substring(i + 1); 
      break; 
     } 
    } 
    if (char2replace.length() > 1) {//you need move this out of loop 
     System.out.println("Error you can only enter one character"); 
    } 


} 
System.out.println(baseString); 
+0

あなたは命を落とす人生です。感謝万円! :-) –

+0

このスレッドにはどのように回答しますか? –

+0

あなたの歓迎:)、このような答えをラベルすることができますhttp://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Jerry06

1

あなたが例えばcommand.replaceAll("and", "a")を使用することができます

0
あなたはにのStringBuilderを使用することができます

次のように、あるインデックスの1文字を置き換えます。

int charIndex = baseString.indexOf(charToBeReplaced); 
StringBuilder baseStringBuilder = new StringBuilder(baseString); 
baseStringBuilder.setCharAt(num2replace, secondChar); 

StringBuilderのsetCharAt()メソッドhereについて詳しくは、こちらを参照してください。

関連する問題