简体   繁体   中英

Java - remove first occurence of char after selected string

In String text in Java, how can I remove all first occurences of a char after a given String? For example:

String s = "Aaaaa bbb cc dd dddd cc ttt d";

Remove first 'd' after 'cc' in the whole string.

Expected result:

String s = "Aaaaa bbb cc d dddd cc ttt ";

Take a look at the Java String#replaceAll method. It lets you supply a regular expression that matches the term you would like to replace, and then provide a replacement string.

In this case, you're trying to match a d following the string cc , and remove it (replace it with a blank string).

The regular expression "(cc.*?)d" will match the first d anywhere after a cc , and then, because of the reluctant quantifier *? , won't match subsequent instances of d .

You can use the capturing group ( (...) ) to take note of what preceded the d , and then reference that in your replacement string.

So the solution becomes string.replaceAll("(cc.*?)d", "$1") , where $1 is a reference to the text captured in the group.

If you want simplicity without regex:

int ddIndex = s.indexOf("dd");
if (ddIndex != -1) {
 int cIndex = s.indexOf('c', ddIndex);
 if (cIndex != -1) {
   s = new StringBuilder(s).deleteCharAt(cIndex).toString();
 }
}
 String s = "Aaaaa bbb cc dd dddd cc ttt d";
int x=  s.indexOf("cc")+1;
    for(int i=x;i<s.length();i++)
   {
     if(s.charAt(i)=='d')
     {s.replace(s.charAt(i),'');break;}
      }

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