Home > DeveloperSection > Forums > How to remove char from string
David Miller

Total Post:30

Points:210
Posted on    February-04-2015 10:18 PM

 OOPS Java  Array List  String 
Ratings:


 1 Reply(s)
 625  View(s)
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?



Sanjay Sharma
Sanjay Sharma

Total Post:45

Points:315
Posted on    February-04-2015 10:41 PM

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


Don't want to miss updates? Please click the below button!

Follow MindStick