2017-03-03 1 views
1

Le problème consiste à remplacer un seul caractère dans une chaîne donnée tout en conservant les autres caractères de la chaîne.Remplacement d'un seul caractère dans une chaîne

Le code est:

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); 

       } 

Répondre

1

Vous presque l'avez fait, ajoutez un compteur dans votre boucle:

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

Vous êtes un sauveteur freaking. Merci un million! :-) –

+0

Comment attribuer un libellé à ce fil? –

+0

votre bienvenue :), vous pouvez étiqueter répondre comme ça http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Jerry06

1

Vous pouvez utiliser command.replaceAll("and", "a") par exemple

0

Vous pouvez utiliser StringBuilder pour remplacer un seul caractère à un index, comme ceci:

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

En savoir plus sur la méthode setCharAt() de StringBuilder here.