SO my problem is that i have a string and i need to search in that string if it is another string. Basically i just want to search if lets say "ala" exists in "balama". I thought about Search by letter by letter but its consuming and if exists more than 2 or 3 words i can't do it. Any suggestions or there is a method in the string? I saw the CompareTO method but doesn't seem to work on partial words in a string. Just the idea to get me started. Thank you for you'r time and consideration.
Asked
Active
Viewed 122 times
-5
-
1Post some code so that we can see what you have tried. People aren't just going to write code for you.. – jonny2k9 Dec 05 '12 at 22:39
-
-1 http://stackoverflow.com/questions/5091057/how-to-find-a-whole-word-in-a-string-in-java – Andrew Dec 05 '12 at 22:39
-
`indexOf`? `matches`? `contains`? Read harder. – Dave Newton Dec 05 '12 at 22:40
-
no need for code i just want the idea. I mean i can't write code if i don't have a basic idea of how to do it. – Vlad Adrian Dec 05 '12 at 22:40
-
I suggest you go through the Java Docs of String. – JHS Dec 05 '12 at 22:41
4 Answers
3
you are looking for String.contains(Charsequence) method.
System.out.println("balama".contains("ala"));// returns true

PermGenError
- 45,977
- 8
- 87
- 106
1
The String
method you are looking for is called indexOf:
String testStr = "Vlad Adrian";
String substr = "ad";
int pstn = testStr.indexOf(substr);
System.out.println(substr + " position in " + testStr + " is " + pstn);
Prints
ad position in Vlad Adrian is 2
If the substring is not found, the method returns -1

amphibient
- 29,770
- 54
- 146
- 240
-
yes thank you very much seems more easier than the pattern&matcher one. – Vlad Adrian Dec 05 '12 at 22:52
-
2you are welcome. let me also add that answers to rudimentary questions like this can often be found in Javadoc for the corresponding class, `String` in this example. you should get in the habit of at least skimming through Javadoc for every class you start using. just my $0.02 – amphibient Dec 05 '12 at 22:56
0
Try searching for a substring in the string. In you know the specific substring to find, you can search specifically for that substring.
Also, if you are using the compareTO method, be sure to implement the appropriate interface.

edxyz
- 9
- 6
-
Implement which interface? They're strings. I think they're already comparable. – Dave Newton Dec 05 '12 at 22:41
-
yes its a good idea but i need to search for more than once and i can do substring of what i find from Indexof from foampile. Its a nice idea. – Vlad Adrian Dec 05 '12 at 22:56