Finding 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

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



Strings are a very important aspect from a programming perspective as many questions can be framed out among strings. There arise wide varied sets of concepts and questions that are pivotal to understanding strings. Now over here will be discussing different ways to play with strings where we will be playing with characters with strings and substrings which is a part of input strings with help of inbuilt methods and also by proposing logic listing wide varied ways as follows: 

Searching a Character in the String

Way 1: indexOf(char c)

It searches the index of specified characters within a given string. It starts searching from the beginning to the end of the string (from left to right) and returns the corresponding index if found otherwise returns -1. 

Note: If the given string contains multiple occurrences of a specified character then it returns the index of the only first occurrence of the specified character. 

Syntax: 

int indexOf(char c)
// Accepts character as argument, Returns index of 
// the first occurrence of specified character 

Way 2: lastIndexOf(char c)

It starts searching backward from the end of the string and returns the index of specified characters whenever it is encountered. 

Syntax: 

public int lastIndexOf(char c)
// Accepts character as argument, Returns an 
// index of the last occurrence specified 
// character

Way 3: indexOf(char c, int indexFrom)

It starts searching forward from the specified index in the string and returns the corresponding index when the specified character is encountered otherwise returns -1. 

Note: The returned index must be greater than or equal to the specified index. 

Syntax: 

public int IndexOf(char c, int indexFrom)

Parameters: 

  • The character to be searched
  • An integer from where searching

Return Type: An index of a specified character that appeared at or after the specified index in a forwarding direction.

Way 4: lastIndexOf(char c, int fromIndex)

It starts searching backward from the specified index in the string. And returns the corresponding index when the specified character is encountered otherwise returns -1. 

Note: The returned index must be less than or equal to the specified index. 

Syntax: 

public int lastIndexOf(char c, int fromIndex)

Way 5: charAt(int indexNumber)

Returns the character existing at the specified index, indexNumber in the given string. If the specified index number does not exist in the string, the method throws an unchecked exception, StringIndexOutOfBoundsException. 

Syntax:

char charAt(int indexNumber)

Example:

Java

import java.io.*;

class GFG {

    public static void main(String[] args)

    {

        String str

            = "GeeksforGeeks is a computer science portal";

        int firstIndex = str.indexOf('s');

        System.out.println("First occurrence of char 's'"

                           + " is found at : "

                           + firstIndex);

        int lastIndex = str.lastIndexOf('s');

        System.out.println("Last occurrence of char 's' is"

                           + " found at : " + lastIndex);

        int first_in = str.indexOf('s', 10);

        System.out.println("First occurrence of char 's'"

                           + " after index 10 : "

                           + first_in);

        int last_in = str.lastIndexOf('s', 20);

        System.out.println("Last occurrence of char 's'"

                           + " after index 20 is : "

                           + last_in);

        int char_at = str.charAt(20);

        System.out.println("Character at location 20: "

                           + char_at);

    }

}

Output

First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

 Way 6: Searching Substring in the String

The methods used for searching a character in the string which are mentioned above can also be used for searching the substring in the string. 

Example

Java

import java.io.*;

class GFG {

    public static void main(String[] args)

    {

        String str

            = "GeeksforGeeks is a computer science portal";

        int firstIndex = str.indexOf("Geeks");

        System.out.println("First occurrence of char Geeks"

                           + " is found at : "

                           + firstIndex);

        int lastIndex = str.lastIndexOf("Geeks");

        System.out.println(

            "Last occurrence of char Geeks is"

            + " found at : " + lastIndex);

        int first_in = str.indexOf("Geeks", 10);

        System.out.println("First occurrence of char Geeks"

                           + " after index 10 : "

                           + first_in);

        int last_in = str.lastIndexOf("Geeks", 20);

        System.out.println("Last occurrence of char Geeks "

                           + "after index 20 is : "

                           + last_in);

    }

}

Output

First occurrence of char Geeks is found at : 0
Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8

Way 7: contains(CharSequence seq): It returns true if the string contains the specified sequence of char values otherwise returns false. Its parameters specify the sequence of characters to be searched and throw NullPointerException if seq is null. 

Syntax: 

public boolean contains(CharSequence seq)

Note: CharSequence is an interface that is implemented by String class, Therefore we use string as an argument in contains() method. 

Example 

Java

import java.io.*;

import java.lang.*;

class GFG {

    public static void main(String[] args)

    {

        String test = "software";

        CharSequence seq = "soft";

        boolean bool = test.contains(seq);

        System.out.println("Found soft?: " + bool);

        boolean seqFound = test.contains("war");

        System.out.println("Found war? " + seqFound);

        boolean sqFound = test.contains("wr");

        System.out.println("Found wr?: " + sqFound);

    }

}

Output

Found soft?: true
Found war? true
Found wr?: false

 Way 8: Matching String Start and End 

  • boolean startsWith(String str): Returns true if the string str exists at the starting of the given string, else false.
  • boolean startsWith(String str, int indexNum): Returns true if the string str exists at the starting of the index indexNum in the given string, else false.
  • boolean endsWith(String str): Returns true if the string str exists at the ending of the given string, else false.

Example:

Java

import java.io.*;

class GFG {

    public static void main(String[] args)

    {

        String str

            = "GeeksforGeeks is a computer science portal";

        System.out.println(str.startsWith("Geek"));

        System.out.println(str.startsWith("is", 14));

        System.out.println(str.endsWith("port"));

    }

}

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

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


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

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!

Like this post? Please share to your friends:
  • Finding word from definition
  • Finding word for definition
  • Finding the word to a definition
  • Finding the word games
  • Finding the word game