Looking back at the original question, we need to find some given keywords in a given sentence, count the number of occurrences and know something about where. I don’t quite understand what «where» means (is it an index in the sentence?), so I’ll pass that one… I’m still learning java, one step at a time, so I’ll see to that one in due time
It must be noticed that common sentences (as the one in the original question) can have repeated keywords, therefore the search cannot just ask if a given keyword «exists or not» and count it as 1 if it does exist. There can be more then one of the same. For example:
// Base sentence (added punctuation, to make it more interesting):
String sentence = "Say that 123 of us will come by and meet you, "
+ "say, at the woods of 123woods.";
// Split it (punctuation taken in consideration, as well):
java.util.List<String> strings =
java.util.Arrays.asList(sentence.split(" |,|\."));
// My keywords:
java.util.ArrayList<String> keywords = new java.util.ArrayList<>();
keywords.add("123woods");
keywords.add("come");
keywords.add("you");
keywords.add("say");
By looking at it, the expected result would be 5 for «Say» + «come» + «you» + «say» + «123woods», counting «say» twice if we go lowercase. If we don’t, then the count should be 4, «Say» being excluded and «say» included. Fine. My suggestion is:
// Set... ready...?
int counter = 0;
// Go!
for(String s : strings)
{
// Asking if the sentence exists in the keywords, not the other
// around, to find repeated keywords in the sentence.
Boolean found = keywords.contains(s.toLowerCase());
if(found)
{
counter ++;
System.out.println("Found: " + s);
}
}
// Statistics:
if (counter > 0)
{
System.out.println("In sentence: " + sentence + "n"
+ "Count: " + counter);
}
And the results are:
Found: Say
Found: come
Found: you
Found: say
Found: 123woods
In sentence: Say that 123 of us will come by and meet you, say, at the woods of 123woods.
Count: 5
In this post, we are finding a word or substring in the String. The String is a sequence of characters and a class in Java.
To find a word in the string, we are using indexOf() and contains() methods of String class.
The indexOf()
method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.
The contains()
method is used to check whether a string contains the specified string or not. It returns a boolean value either true or false. If the specified string is found then it returns true, false otherwise.
Time for an Example:
Let’s create an example to find a word in the string. Here, we are using indexOf() method that returns an index of the specified substring. See the example below.
public class Main {
public static void main(String[] args){
String str = "This sentance contains find me string";
System.out.println(str);
// find word in String
String find = "find me";
int i = str.indexOf(find);
if(i>0)
System.out.println(str.substring(i, i+find.length()));
else
System.out.println("string not found");
}
}
This sentance contains find me string
find me
Example 2
Let’s create another example to find a word in the string. Here, we are using the contains()
method that returns true, if the specified string is found. See the example below.
public class Main {
public static void main(String[] args){
String str = "This sentance contains find me string";
System.out.println(str);
// find word in String
String find = "find me";
boolean val = str.contains(find);
if(val)
System.out.println("String found: "+find);
else
System.out.println("string not found");
}
}
This sentance contains find me string
String found: find me
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Given a string, extract words from it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z.
Examples:
Input : Funny?? are not you? Output : Funny are not you Input : Geeks for geeks?? Output : Geeks for geeks
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
We have discussed a solution for C++ in this post : Program to extract words from a given String
We have also discussed basic approach for java in these posts : Counting number of lines, words, characters and paragraphs in a text file using Java and Print first letter in word using Regex.
In this post, we will discuss Regular Expression approach for doing the same. This approach is best in terms of Time Complexity and is also used for large input files. Below is the regular expression for any word.
[a-zA-Z]+
import
java.util.regex.Matcher;
import
java.util.regex.Pattern;
public
class
Test
{
public
static
void
main(String[] args)
{
String s1 =
"Geeks for Geeks"
;
String s2 =
"A Computer Science Portal for Geeks"
;
Pattern p = Pattern.compile(
"[a-zA-Z]+"
);
Matcher m1 = p.matcher(s1);
Matcher m2 = p.matcher(s2);
System.out.println(
"Words from string ""
+ s1 +
"" : "
);
while
(m1.find()) {
System.out.println(m1.group());
}
System.out.println(
"Words from string ""
+ s2 +
"" : "
);
while
(m2.find()) {
System.out.println(m2.group());
}
}
}
Output:
Words from string "Geeks for Geeks" : Geeks for Geeks Words from string "A Computer Science Portal for Geeks" : A Computer Science Portal for Geeks
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Like Article
Save Article
Java Program to Search Word in a String
In java programming, indexOf method is used to find the index of sub string in the string.
indexOf method returns index if sub string is found in the string, otherwise returns -1.
This java program is used to check whether word or substring is found in the string or not.
Here string and word are both user inputs.
indexOf method is used to search the word in string from left to right.
import java.util.Scanner; public class SearchString { public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.println("Search word in string"); System.out.println("-----------------------"); System.out.print("Enter String: "); String str = sc.nextLine(); System.out.print("Enter word to search: "); String word =sc.next(); int index = str.indexOf(word); if(index >= 0){ System.out.print("Search Found index: "); System.out.println(index); } else { System.out.println("No Search Found!"); } } }
Output:
D:Java_Programs>javac SearchString.java D:Java_Programs>java SearchString Search word in string ---------------------- Enter String: This is testing in progress Enter word to search: testing Search Found index: 8 D:Java_Programs>javac SearchString.java D:Java_Programs>java SearchString Search word in string --------------------- Enter String: This is testing in progress Enter word to search: searching No Search Found!
Java Program to Search Word in a String from Right to Left
lastIndexOf method returns index if sub string is found in the string and matches from end to beginning of the string, otherwise returns -1.
import java.util.Scanner; public class SearchString { public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.println("Search word in string from right to left"); System.out.println("------------------------------------------"); System.out.print("Enter String: "); String str = sc.nextLine(); System.out.print("Enter word to search: "); String word =sc.next(); int index = str.lastIndexOf(word); if(index >= 0){ System.out.print("Search Found index: "); System.out.println(index); } else { System.out.println("No Search Found!"); } } }
Output:
D:Java_Programs>javac SearchString.java D:Java_Programs>java SearchString Search word in string from right to left ------------------------------------------ Enter String: This is testing codingpointer.com and is to identify issues! Enter word to search: is Search Found index: 53 D:Java_Programs>javac SearchString.java D:Java_Programs>java SearchString Search word in string from right to left ------------------------------------------ Enter String: This is testing in progress Enter word to search: searching No Search Found!
Problem Description
How to search a word inside a string?
Solution
This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1.
public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1) { System.out.println("Hello not found"); } else { System.out.println("Found Hello at index " + intIndex); } } }
Result
The above code sample will produce the following result.
Found Hello at index 0
This example shows how we can search a word within a String object
public class HelloWorld { public static void main(String[] args) { String text = "The cat is on the table"; System.out.print(text.contains("the")); } }
Result
The above code sample will produce the following result.
true
java_strings.htm
In this code example we are going to learn how to find a specific word or text inside a string. For this example we will utilize the java.lang.String
class. The String
class provides a method called String.indexOf()
. It takes an argument of a String
, which is the sub string that we want to find in the other string. You can imagine the sub string as a needle that we are going to find in the haystack.
If the word found more than once in the string, the indexOf()
method returns the first index of a sub string found in the specified string. If the sub string can’t be found this method returns -1
. The index of string returns by this method begin at zero. It means that the first letter in the string have the index number 0
.
Another way that we can use is the String.contains()
method. This method introduced in JDK 1.5. The method simply return a boolean value which is true
or false
indicating whether the string in search is found in the haystack. Let’s see the snippet below:
package org.kodejava.lang;
public class StringContainsExample {
public static void main(String[] args) {
String haystack = "Kodejava - Learn Java by Examples";
// Checks to see if the word "Java" is found in the haystack
// variable.
String needle = "Java";
if (haystack.indexOf(needle) != -1) {
System.out.println("Found the word " + needle +
" at index number " + haystack.indexOf(needle));
} else {
System.out.println("Can't find " + needle);
}
// Or use the String.contains() method if you are not interested
// with the index of the word.
if (haystack.contains(needle)) {
System.out.println("Eureka we've found Java!");
}
}
}
Running the example gave you the following result:
Found the word Java at index number 17
Eureka we've found Java!
- Author
- Recent Posts
A programmer, runner, recreational diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕, every little bit helps, thank you 🙏
Views: 60,427