41

I want to check if my string contains a + character.I tried following code

s= "ddjdjdj+kfkfkf";

if(s.contains ("\\+"){
 String parts[] = s.split("\\+);
  s=  parts[0]; // i want to strip part after  +

}

but it doesnot give expected result.Any idea?

user93796
  • 18,749
  • 31
  • 94
  • 150
  • 2
    Please read http://tinyurl.com/so-hints - it's useless to say it doesn't give the expected result without saying what you expected and what you actually got. – Jon Skeet Apr 08 '12 at 06:21

3 Answers3

95

You need this instead:

if(s.contains("+"))

contains() method of String class does not take regular expression as a parameter, it takes normal text.


EDIT:

String s = "ddjdjdj+kfkfkf";

if(s.contains("+"))
{
    String parts[] = s.split("\\+");
    System.out.print(parts[0]);
}

OUTPUT:

ddjdjdj
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • That doesn't get the part before the plus though, which is what it sounds like the OP really wants. – Jon Skeet Apr 08 '12 at 06:21
  • When I posted my comment your answer *only* contained the call to `String.contains`. – Jon Skeet Apr 08 '12 at 06:38
  • (Having just looked at the question again, I'd missed the fact that he was already calling contains. It's too early. Doh. But pointing out that the rest of the code was already okay would have been useful...) – Jon Skeet Apr 08 '12 at 06:46
13

Why not just:

int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
    String before = s.substring(0, plusIndex);
    // Use before
}

It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:

Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");

If you're going to use split (either the built-in version or Guava) you don't need to check whether it contains + first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:

// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];

Note that writing String[] parts is preferred over String parts[] - it's much more idiomatic Java code.

rohan-patel
  • 5,772
  • 5
  • 45
  • 68
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);
cloudygoose
  • 608
  • 1
  • 6
  • 16