简体   繁体   中英

Remove char from String

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?

public String replace(char oldChar, char newChar) will replace all occurrences of oldChar in this string with newChar.

You should consider using public String replaceFirst(String regex,String replacement) which replaces the first substring of this string that matches the given regular expression with the given replacement.

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

you need to first find the index of first occurrence using indexof() metohd, then you can find the text before and after the targeted char by substring() method , at the end you need to use concat() to attach them.

Str.replaceFirst() also works well

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

You may choose to use public String replaceFirst(String regex, String replacement)

regex -- This is the regular expression to which this string is to be matched.
replacement -- This is the string to be substituted for each match.

Since in your code, you just want to replace first occurence of repeated charecter, you may replace it with blank like below code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM