开发者

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, jus开发者_开发问答t +'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");


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
*/


Sorry I downvoted you guys because the answer is: use StringBuffer.deleteCharAt(int Index)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜