To find a string in a sentence in Java, you can use the contains()
method of the String
class.
Here's an example of how to find a string in a sentence in Java:
String sentence = "The quick brown fox jumps over the lazy dog."; String target = "fox"; if (sentence.contains(target)) { System.out.println("Found string: " + target); } else { System.out.println("String not found: " + target); }
In the above example, the contains()
method is used to search for the target
string in the sentence
. If the target
string is found, a message is printed to the console. If the target
string is not found, a different message is printed.
Alternatively, you can use the indexOf()
method of the String
class to find the index of the first occurrence of the target
string in the sentence
. For example:
String sentence = "The quick brown fox jumps over the lazy dog."; String target = "fox"; int index = sentence.indexOf(target); if (index != -1) { System.out.println("Found string at index " + index); } else { System.out.println("String not found: " + target); }
In the above example, the indexOf()
method returns the index of the first occurrence of the target
string in the sentence
. If the string is not found, the method returns -1.