Reputation: 3917
I have string like:
This.is.a.great.place.too.work.
(or)
This/is/a/great/place/too/work/
I want to see if this string has the word "place".
If they are word in a string I used contains("place"). as this is all one string I tried split but it is giving syntax error . can you please let me know how to get it?
string.contains("place") works
String.split(".").contains("place") Error
Upvotes: 0
Views: 1266
Reputation: 347
try this
string.split(pattern);
String[] strings = s.split(".")
Split will give array of strings which are splitted based on the paramater .
you cannot apply contains on string array , instead use the following
boolean flag = string.contains("required_pattern");
Upvotes: 1
Reputation: 33534
Try it simply like this.......
String s = "This/is/a/great/place/too/work/";
String ss = "This.is.a.great.place.too.work";
System.out.println(s.contains("place"));
System.out.println(ss.contains("place"));
Upvotes: 1
Reputation: 52185
Besides using the .contains
method, which I think is best, you seem to want to build a data structure and search through it. To do something like that, you will need to do this:
String str = "This.is.a.great.place.too.work.";
String[] splitWords = str.split("\\."); //The . is a special character in regex language, thus needs to be escaped. Alternatively you could use \\W which will split the string where ever it finds a character which is not a letter, digit or underscore.
List<String> words = Arrays.asList(splitWords);
System.out.println(words.contains("place"));
Alternatively, you could use the indexOf(String str)
method like so:
if (str.indexOf("place") > 0)
{
System.out.println("String Exists");
}
Upvotes: 1
Reputation: 1241
Try to split with "//."
String string = "This.is.a.great.place.too.work.";
System.out.println(string.split("\\.")[0]);
Upvotes: 2
Reputation: 5837
use string.split("\\.").contains("place")
this should work. .(dot)
is a reserved character in regular expression, You need to escape that by using \\.
.
Upvotes: 2
Reputation: 37566
you dont need to split the string in order to use the containts methode.
string str = "This.is.a.great.place.too.work.";
boolean found = str.contains("substring"); // should return true or false
Alternative you can use the:
str.indexOf("substring") > 0
to determine if the substring is in the string
To do this in one single line you can do something like:
Arrays.toString(str.split(".")).Contains("substring")
Upvotes: 1
Reputation: 17839
you can use
String str = "This.is.a.great.place.too.work.";
boolean exists = str.contains("place");
This checks to find the word place in a String and returns true if found, false if not
Upvotes: 1