rickygrimes
rickygrimes

Reputation: 2716

Delete every occurence of a character from a String

I have the below program that I have written to delete every character from a String.

public static String removeMultipleCharsFromStr(String str,char temp) {
    StringBuffer sb = new StringBuffer();
    for(int i=0;i<str.length();i++) {
        sb.append(str.charAt(i));
    }       
    for(int i=0;i<sb.length();i++) {
        if(Character.toLowerCase(sb.charAt(i)) == Character.toLowerCase(temp)) {
            sb.deleteCharAt(i);                             
        }
    }       
    System.out.println("Final string: " +sb.toString());
    return sb.toString();
}

When I invoke the method, it doesn't remove every occurrence of the character though. Can someone please tell me what mistake am I making here?

public class RemoveChar {
public static void main(String[] args) {        
    removeMultipleCharsFromStr("SSSSSaerty", 'S');
}

Outputs - Final string: SSaerty

Please advise. Also, I understand there can be a hundred other solutions to my question. I'd appreciate if you could let me know the mistakes in my code rather than suggesting your solution ;)

Upvotes: 0

Views: 116

Answers (3)

padawan
padawan

Reputation: 1315

Just add i--; after sb.deleteCharAt(i);. This way, you continue where you left off. Otherwise, you skip the next char because the size of your StringBuffer reduces by 1.

Upvotes: 0

MAV
MAV

Reputation: 7457

Not sure what happened to the other answer, but let's see what happens in your algorithm.

When everything is placed in the StringBuffer it will look something like this:

       i
Index: 0 1 2 3 4 5 6 7 8 9
Value: S S S S S a e r t y

In your first iteration (in the last loop) you are looking at index 0 (i is 0). The char at index 0 is S, so you remove it. Now your buffer looks like this:

         i
Index: 0 1 2 3 4 5 6 7 8
Value: S S S S a e r t y 

The first S is gone, but instead of leaving index 0 empty, all the other chars moved 1 place to the left. In your next iteration i is 1. This means that you never look at the new value at index 0.

The same thing happens when you go from 1 to 2 and 2 to 3. In the end that means you have skipped 2 S values. If you increase the number of continuous S values, you will see more of them in the output.

           i
Index: 0 1 2 3 4 5 6 7
Value: S S S a e r t y 

             i
Index: 0 1 2 3 4 5 6
Value: S S a e r t y     <-- See?

I'd appreciate if you could let me know the mistakes in my code rather than suggesting your solution ;)

Fair enough. Good luck with it. :)

Upvotes: 3

Dekker1
Dekker1

Reputation: 5786

The for-loop advances while you're deleting a character. So another character will be on the index position that you've just passed. An fix would be:

public static String removeMultipleCharsFromStr(String str,char temp) {
    StringBuffer sb = new StringBuffer();
    for(int i=0;i<str.length();i++) {
        sb.append(str.charAt(i));
    }       
    for(int i=0;i<sb.length();i++) {
        if(Character.toLowerCase(sb.charAt(i)) == Character.toLowerCase(temp)) {
            sb.deleteCharAt(i);
            i--;      
        }
    }       
    System.out.println("Final string: " +sb.toString());
    return sb.toString();
}

Although you might consider using the standard replacement methods as suggested in the comments:

str.replaceAll(String.valueOf(temp),"")

Upvotes: 0

Related Questions