HOW TO REMOVE CHAR FROM STRING

David Miller

Total Post:30

Points:210
Posted by  David Miller
 983  View(s)
Ratings:
Rate this:

I want to remove a letter from a String - But only a single occurrence of the letter:

Example: if my word is "aaba" and I want to remove an 'a':

Output would be "aba" - Only the first 'a' is removed. (Not all the 'a's)

I came up with this:

String word = "aaba"

String newWord = word.replace(a, "");

The problem is that newWord='b' instead of 'aba'

Can someone please help? For some reason I am having much difficulty with this seemingly simple problem. What is the best way to solve this problem?

Do I need to create an ArrayList of some sort?

  1. Sanjay Sharma

    Post:45

    Points:315
    Re: How to remove char from string

    String replaceFirst() Method

    public String replaceFirst(String regex, String replacement)

    Parameters:

    Here is the detail of parameters:

    regex -- the regular expression to which this string is to be matched.

     

    replacement -- the string which would replace found expression.

    Code

     public static void main(String[] args) {

            String word = "aaba";

            String newWord = word.replaceFirst("a", "");

            System.out.println(newWord);

        }

    Output

    aba

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!