Reputation: 399
Today I was trying to detect if a string contains a dot, but my code isn't working
String s = "test.test";
if(s.contains("\\.")) {
System.out.printLn("string contains dot");
}
Upvotes: 20
Views: 84384
Reputation: 391
The easiest way is to check with a .contains()
statement.
Note: .contains()
works only for strings.
From
String s = "test.test";
if(s.contains("\\.")) {
System.out.printLn("string contains dot");
}
To
String s = "test.test";
if(s.contains(".")) {
System.out.printLn("string contains dot");
}
Do like this to check any symbol or character in a string.
Upvotes: 0
Reputation: 861
Try this,
String k="test.test";
String pattern="\\.";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(k);
if(m.find()){
System.out.println("Contains a dot");
}
}
Upvotes: 0
Reputation: 9839
Sometimes you will need to find a character and do something with it, a similar check can also be done using .indexOf('.')
, for instance:
"Mr. Anderson".indexOf('.'); // will return 2
The method will return the index position of the dot, if the character doesn't exist, the method will return -1, you can later do a check on that.
if ((index = str.indexOf('.'))>-1) { .. do something with index.. }
Upvotes: 3
Reputation: 8497
contains()
method of String class does not take regular expression as a parameter, it takes normal text.
String s = "test.test";
if(s.contains("."))
{
System.out.println("string contains dot");
}
Upvotes: 27
Reputation: 85779
String#contains
receives a plain CharacterSequence
e.g. a String
, not a regex. Remove the \\
from there.
String s = "test.test";
if (s.contains(".")) {
System.out.println("string contains dot");
}
Upvotes: 16