-2

would you please let me know if there is a way(java) to check is a string is exist in a long string? example: check if the word hello is exist in this string "abcdffgfghdshghelloasdf" in this case true sould be returned .

Best Regards, Maya

maya
  • 41
  • 1
  • 6

2 Answers2

0

This can be done simply by using contains method

String orig="abcdffgfghdshghelloasdf";
if (orig.contains("hello"))
    return true;
else
    return false;
Grim
  • 1,938
  • 10
  • 56
  • 123
BountyHunter
  • 1,413
  • 21
  • 35
  • 1
    Using something like toLowerCase() or toUpperCase() might be useful as well depending of the context. – Rajind Ruparathna Dec 03 '16 at 10:40
  • 1
    Why not just `return orig.contains("hello")`? Also note that question had `hello` is all lowercase and expected a `true` result, whereas your code returns `false` since mixedcase `Hello` is not in string. – Andreas Dec 03 '16 at 10:46
  • FFS! Please don't use the `if (exp) true else false` anti-pattern. For one thing, it gives me a migraine. – Michael Lorton Dec 03 '16 at 12:01
0

In Java you can do that in many ways, for example by using methods from String class:

Contains method - takes CharSequence as parameter:

boolean checkContains(){
    String orig="abcdffgfghdshghelloasdf";
    return orig.contains("hello");
}

Matches method - takes regex as parameter:

boolean checkMatches(){
    String orig="abcdffgfghdshghelloasdf";
    return orig.matches(".*hello.*");
}

Both of them are really fast, so there is no big difference which of them you will use.

Michał Szewczyk
  • 7,540
  • 8
  • 35
  • 47