0

I need to dynamically check for presence of char sequence "(Self)" in a string and parse it out.

So if my string say myString is

"ABCDEF (Self)"

it should return myString as

"ABCDEF"

What is the best way of doing it? Can it be done in a single step?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29 returns the string – Leo Sep 30 '14 at 09:08
  • Regular Expressions are what you require check out my answer. – Darshan Lila Sep 30 '14 at 09:14

5 Answers5

2

You may use the replace function as follows:

myString = myString.replace(" (Self)","");

Here, read more about things to note with String.replace or the function definition itself. Note that it is overloaded with a char variant, so you can do two kinds of things with a similar function call.

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You may use the replaceAll method from the String class as follows:

myString = myString.replaceAll(Pattern.quote("(Self)"), ""));
Benjamin
  • 1,816
  • 13
  • 21
  • @Hamad I'm confused, i just provided an answer. It's a different answer than the accepted one, but it's not wrong so far... `"ABCDEF (Self)".replaceAll(Pattern.quote("(Self)"), ""));` returns `ABCDEF `... Am i missing something? – Benjamin Sep 30 '14 at 10:51
  • Sorry! it was my mistake, i tried to select low quality answer but in haste the other one was selected – Hamad Sep 30 '14 at 11:34
  • as a sorry i am up voting ur answer – Hamad Sep 30 '14 at 11:42
0

Try following:

      String test="ABCDEF (Self)";
      test=test.replaceAll("\\(Self\\)", "");
      System.out.println(test.trim());

Output :

ABCDEF 

The dig is to use Regular Expressions for more on it visit this link.

And the code won't have a problem if there is no Self in string.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
0

Just check out the String class' public methods.

String modifyString(String str) {
    if(str.contains("(Self)")) {
        str = str.replace("(Self)", "");
        str = str.trim();
    }
    return str;
}
Atuos
  • 501
  • 3
  • 12
0

From the question, I understand that from source string ABCDEF (Self) also the space between F and ( should be removed. I would recommend to use regEx if you are comfortable with it, else:

 String OrigString = "ABCDEF (Self)";
 String newString= OrigString.replaceAll("\\(Self\\)", "").trim();
 System.out.println("New String : --" +newString+"--");

The Regular Expression for your case would be:

\s*\(Self\)\s*

Tested Java Code using regular expression would be:

  String newRegExpString = OrigString.replaceAll("\\s*\\(Self\\)\\s*", "");
  System.out.println("New String : -" +newRegExpString+"--");

Output:

New String : --ABCDEF--
New String : -ABCDEF--
ngrashia
  • 9,869
  • 5
  • 43
  • 58