Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if string contains '+' character [duplicate]

Tags:

java

string

match

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?

like image 291
user93796 Avatar asked Apr 08 '12 06:04

user93796


People also ask

How do you check if a character is repeated in a string C#?

string repeatedWord = "woooooooow"; for (int i = 0; i < repeatedWord. Count(); i++) { if (repeatedWord[i] == repeatedWord[i+1]) { // .... } } The code works but it will always have an error because the last character [i + 1] is empty/null.


2 Answers

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 
like image 125
Eng.Fouad Avatar answered Sep 22 '22 04:09

Eng.Fouad


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.

like image 25
Jon Skeet Avatar answered Sep 24 '22 04:09

Jon Skeet