简体   繁体   中英

Removing char from string?

I am searching for the following text in an input string: +Bob

If the program finds +Bob , I want it to remove the + before Bob

However, I do not want the program to eliminate all + 's, just + 's before or after Bob, with or without intervening whitespace. So a string for example of: + Bob still counts as +Bob .

String str = "+Bob foo + bar";
str = str.replace("+Bob", "Bob");
System.out.println(str);

Bob foo + bar

To handle a space between + and Bob you can use regular expressions:

String str = "+Bob foo + bar";
str = str.replaceAll("\\+\\s*Bob", "Bob");

To check for a plus afterwards, use

str = str.replaceAll("Bob\\s*\\+", "Bob");

抱歉,我拒绝了你们的投票,因为答案是:使用StringBuffer.deleteCharAt(int Index)

public class Test {
  public static void main(String[] args) throws Exception {
    String regexp = "(?)\\+(\\s?)+Bob";
    System.out.println("+Bob foo + bar".replaceAll(regexp, "Bob"));
    System.out.println("+  Bob foo + bar".replaceAll(regexp, "Bob"));
    System.out.println("+  Bob foo + bar  +Bob".replaceAll(regexp, "Bob"));
    System.out.println("+  Bob foo + bar  +    Bob".replaceAll(regexp, "Bob"));
 }
}
/* output :
Bob foo + bar
Bob foo + bar
Bob foo + bar  Bob
Bob foo + bar  Bob
*/

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