Как найти слово в тексте 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

Теги: java, string, символ, поиск, строка, метод, буква, знак, contains

В этой статье мы рассмотрим, как выполнять поиск букв и других символов в строке Java, а также как проверять, находится ли нужный символ, буква или слово в строке, начиная с указанного индекса.

JavaPro_970x90-20219-3b63e7.png

Строкой в Java называют упорядоченную последовательность символов. Как правило строка в Java — это один из основных носителей текстовой информации.

Для работы со строками в Java применяют классы String, StringBuilder и StringBuffer. Класс String включает методы, возвращающие позицию символа либо подстроки в строке:
— indexOf() — для поиска с начала строки;
— lastIndexOf() — для выполнения поиска с конца строки.

Таким образом, если метод indexOf() найдёт заданную букву, символ либо строку, он вернёт индекс, то есть порядковый номер. Если не найдёт, будет возвращено -1. Также он позволяет искать символ или букву, начиная с указанного индекса.

Кроме того, стоит добавить, что класс String включает в себя ещё и метод contains, возвращающий true, когда в строке содержится заданная последовательность символов. Этот метод рекомендуется использовать лишь тогда, когда вам просто нужно узнать о существовании подстроки в строке, при этом позиция не имеет значения.

Метод indexOf()

Библиотека метода:


Синтаксис следующий:

public int indexOf(char ch)
public int indexOf(char ch, int fromIndex)

либо

public int indexOf(String s)
public int indexOf(String s, int fromIndex)

Соответственно, вызвать метод можно тоже несколькими способами:

int index = str1.indexOf(myChar);
int index = str1.indexOf(myChar, start);

или:

int index = str1.indexOf(myString);
int index = str1.indexOf(myString, start);

Представьте, что нам нужно отыскать в строке индекс первого вхождения требуемого символа/буквы, а также нужного слова. Как уже было сказано выше, метод indexOf() вернёт нам индекс первого вхождения, а в случае неудачи — вернёт -1.

JavaSpec_970x90-20219-e8e90f.png

Посмотрите на следующий код:

public class Main {
   public static void main(String[] args) {
      String str = "Otus — онлайн-образование";

      int indexM = str.indexOf("з"); // Ищем символ в строке
      int indexJava = str.indexOf("онлайн"); // Ищем слово в строке

      if(indexM == - 1) {
         System.out.println("Символ "з" не найден.");
      } else {
         System.out.println("Символ "з" найден, его индекс: " + indexM);
      }

      if(indexJava == - 1) {
         System.out.println("Слово "онлайн" не найдено.");
      } else {
         System.out.println("Слово "онлайн" найдено, его индекс: " + indexJava);
      }
   }
}

Результат получим следующий:

Символ "з" найден, его индекс: 18
Слово "онлайн" найдено, его индекс: 7

Метод contains

Бывают ситуации, когда нам необходимо проверить, содержит ли наша строка конкретный символ/букву либо слово. Нижеследующий Java-код продемонстрирует и этот пример:

public class Main {
   public static void main(String[] args) {
      String str = "Otus — онлайн-образование";
      System.out.println("Слово "Otus" есть в строке str? Ответ: " + str.contains("Otus"));
      System.out.println("Символ "z" присутствует в строке str? Ответ: " + str.contains("z"));
   }
}

В этом случае результат будет следующим:

Слово "Otus" есть в строке str? Ответ: true
Символ "z" присутствует в строке str? Ответ: false

Как видите, выполнять поиск букв и других символов в строке Java совсем несложно, и наши элементарные примеры убедительно это подтверждают. Если же вы хотите получить более продвинутые навыки по Java-разработке, добро пожаловать на наш курс:

JavaPro_970x550-20219-8420e5.png

Описание проблемы

Как найти символ или слово в строке?

Решение 1: когда нужно найти индекс первого вхождения

Следующий пример показывает как найти символ или слово в строке в Java с помощью метода indexOf(). Метод вернет индекс первого вхождения, если символ или слово не будет найдено, то метод вернет -1.

public class Example {
   public static void main(String[] args) {
      String str = "Привет, java-программист!";
      
      int indexM = str.indexOf("м"); // Нахождение символа в строке
      int indexJava = str.indexOf("java"); // Нахождение слова в строке
      
      if(indexM == - 1) {
         System.out.println("Символ "м" не найден.");
      } else {
         System.out.println("Символ "м" найден в индексе " + indexM);
      }
      
      if(indexJava == - 1) {
         System.out.println("Слово "java" не найдено.");
      } else {
         System.out.println("Слово "java" найдено в индексе " + indexJava);
      }
   }
}

Результат

Получим следующий результат:

Символ "м" найден в индексе 19
Слово "java" найдено в индексе 8

Решение 2: когда нужно узнать есть ли в строке данный символ или слово

Ниже продемонстрирован пример, который позволяет в Java узнать присутствует ли данный символ или слово в строке.

public class Example {
   public static void main(String[] args) {
      String str = "Привет, java-программист!";
      System.out.println("Слово "программист" есть в строке str? Ответ: " + str.contains("программист"));
      System.out.println("Символ "б" присутствует в строке str? Ответ: " + str.contains("б"));
   }
}

Результат

Получим следующий результат:

Слово "программист" есть в строке str? Ответ: true
Символ "б" присутствует в строке str? Ответ: false

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.

Last Updated :
16 Feb, 2023

Like Article

Save Article

Для того, чтобы найти подстроку в строке в Java, вы можете использовать метод indexOf() или lastIndexOf() класса String.
Эти методы позволяют найти индекс первого (или последнего) вхождения заданной подстроки в строке. Если подстрока не найдена, методы возвращают -1.

Например, чтобы найти индекс первого вхождения подстроки “world” в строке “Hello world!”, вы можете использовать следующий код:

String str = "Hello world!";
int index = str.indexOf("world");
System.out.println(index); // => 6

Также можно использовать метод contains() для проверки наличия подстроки в строке без необходимости получать ее индекс.

String str = "Hello world!";
boolean contains = str.contains("world");
System.out.println(contains); // => true

Добавить комментарий