-5

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.

Vlad Adrian
  • 3
  • 1
  • 4

4 Answers4

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
  • 2
    you 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
0

I suggest you examine the use of Regular Expressions. The Sun site has a great tutorial on them here In particular launch their Test Harness - it should provide the answer

Katana24
  • 8,706
  • 19
  • 76
  • 118