haileysponses
haileysponses

Reputation: 9

Java: how to take out a letter of a string while printing the rest of the letter in the string

So I'm barely learning Java and I'm having a hard time using loops. I'm supposed to write a program that let the user enter a word and enter a letter they want to remove while printing out the other letters.

here is what I have right now:

System.out.print("Please enter a word: ");
String word = kbreader.nextLine();  
System.out.print("Enter the letter you want to remove: ");
for (int k = 0; k <= word.length(); k ++)
{
    String remove = kbreader.nextLine(); 
    String word2 = word.charAt(k) + "";
    String remove2 = remove.charAt(0) + "";
    if (!word2.equals(remove2))
    {
        System.out.print(word2);
    }
} 

here is an example:

enter a word: aaabxaaa

enter a letter you want to remove: a

bx

Upvotes: 0

Views: 1059

Answers (3)

AppleCiderGuy
AppleCiderGuy

Reputation: 1297

This is how you can do it :

System.out.print("Please enter a word: ");

String word = kbreader.nextLine();

System.out.print("Enter the letter you want to remove: ");

//read the char to remove just once before starting the loop
char remove = kbreader.nextLine().charAt(0); 

for (int k = 0; k <= word.length(); k ++)
{ 

    char word_char = word.charAt(k);
    //check if the current char is equal to char required to be removed
    if (word_char != remove)
    {
       System.out.print(word_char);
    }

} 

Upvotes: 1

Mark Melgo
Mark Melgo

Reputation: 1478

Use public String replace(char oldChar, char newChar) function in java.

Modify to this :

System.out.print("Please enter a word: ");
String word = kbreader.nextLine();
System.out.print("Enter the letter you want to remove: ");
String remove = kbreader.nextLine();
word = word.replace(remove ,"");
System.out.print(word);

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522141

One simple way to handle this would be to just use String#replace here:

System.out.println(word.replace(remove, ""));

This would remove all instances of the string remove, which in your case would just be a single letter.

Another way to do this would be to iterate your input string, and then selectively print only those characters which do not match the character to be removed:

char charRemove = remove.charAt(0);
for (int i=0; i < s.length(); i++){
    char c = s.charAt(i);
    if (c != charRemove) System.out.print(c);
}

Upvotes: 3

Related Questions