Get word in string java

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

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • 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

    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



    The Java String class substring() method returns a part of the string.

    We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1.

    There are two types of substring methods in Java string.

    Signature

    If we don’t specify endIndex, the method will return all the characters from startIndex.

    Parameters

    startIndex : starting index is inclusive

    endIndex : ending index is exclusive

    Returns

    specified string

    Exception Throws

    StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.

    • if the start index is negative value
    • end index is lower than starting index.
    • Either starting or ending index is greater than the total number of characters present in the string.

    Internal implementation substring(int beginIndex)

    Internal implementation substring(int beginIndex, int endIndex)

    Java String substring() method example

    FileName: SubstringExample.java

    Test it Now

    Output:

    Java String substring() Method Example 2

    FileName: SubstringExample2.java

    Output:

    Javatpoint
    point
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 10
    

    Applications of substring() Method

    1) The substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as «singh». The following program shows the same.

    FileName: SubstringExample3.java

    Output:

    Yuvraj Singh
    Harbhajan Singh
    Gurjit Singh
    Sandeep Singh
    Milkha Singh
    

    2) The substring() method can also be used to check whether a string is a palindrome or not.

    FileName: SubstringExample4.java

    Output:

    madam is a palindrome.
    rock is not a palindrome.
    eye is a palindrome.
    noon is a palindrome.
    kill is not a palindrome.
    


    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

    Понравилась статья? Поделить с друзьями:
  • Get word from string php
  • Get word from pdf
  • Get values from excel cell to vba
  • Get tongue round the word
  • Get to visual basic in excel