Как найти string в string java

Possible Duplicate:
How to see if a substring exists inside another string in Java 1.4

How would I search for a string in another string?

This is an example of what I’m talking about:

String word = "cat";
String text = "The cat is on the table";
Boolean found;

found = findInString(word, text); //this method is what I want to know

If the string «word» is in the string «text», the method «findInString(String, String)» returns true else it returns false.

Community's user avatar

asked Feb 14, 2012 at 11:28

Meroelyth's user avatar

0

That is already in the String class:

String word = "cat";
String text = "The cat is on the table";
Boolean found;

found = text.contains(word);

answered Feb 14, 2012 at 11:30

Stephan's user avatar

StephanStephan

4,3753 gold badges26 silver badges49 bronze badges

Use the String.indexOf(String str) method.

From the JavaDoc:

Returns the index within this string of the first occurrence of the
specified substring.

Returns: if the string argument occurs as a substring within this
object, then the index of the first character of the first such
substring is returned; if it does not occur as a substring, -1 is
returned.

So:

boolean findInString(word, text)
{
  return text.indexOf(word) > -1;
}

answered Feb 14, 2012 at 11:29

Andy's user avatar

AndyAndy

8,8201 gold badge30 silver badges39 bronze badges

word.contains(text)

Take a look at the JavaDocs.

Returns true if and only if this string contains the specified
sequence of char values.

answered Feb 14, 2012 at 11:30

Marcelo's user avatar

MarceloMarcelo

4,5607 gold badges28 silver badges45 bronze badges

This can be done by using

boolean isContains = text.contains(word);

answered Feb 14, 2012 at 11:32

Chandra Sekhar's user avatar

Chandra SekharChandra Sekhar

18.7k14 gold badges81 silver badges123 bronze badges

found = text.contains(word);

answered Feb 14, 2012 at 11:32

Juzer Ali's user avatar

Juzer AliJuzer Ali

4,1013 gold badges34 silver badges62 bronze badges

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a String, the task is to insert another string in between the given String at a particular specified index in Java.

    Examples:

    Input: originalString = "GeeksGeeks", 
                  stringToBeInserted = "For", 
                  index = 4
    Output: "GeeksForGeeks"
    
    
    Input: originalString = "Computer Portal", 
                  stringToBeInserted = "Science ", 
                  index = 8
    Output: "Computer Science Portal"
    

    The various methods to do this are as follows:

    1. Without using any pre-defined method

      Approach:

      1. Get the Strings and the index.
      2. Create a new String
      3. Traverse the string till the specified index and copy this into the new String.
      4. Copy the String to be inserted into this new String
      5. Copy the remaining characters of the first string into the new String
      6. Return/Print the new String

      Below is the implementation of the above approach:

      Program:

      import java.lang.*;

      class GFG {

          public static String insertString(

              String originalString,

              String stringToBeInserted,

              int index)

          {

              String newString = new String();

              for (int i = 0; i < originalString.length(); i++) {

                  newString += originalString.charAt(i);

                  if (i == index) {

                      newString += stringToBeInserted;

                  }

              }

              return newString;

          }

          public static void main(String[] args)

          {

              String originalString = "GeeksGeeks";

              String stringToBeInserted = "For";

              int index = 4;

              System.out.println("Original String: "

                                 + originalString);

              System.out.println("String to be inserted: "

                                 + stringToBeInserted);

              System.out.println("String to be inserted at index: "

                                 + index);

              System.out.println("Modified String: "

                                 + insertString(originalString,

                                                stringToBeInserted,

                                                index));

          }

      }

      Output:

      Original String: GeeksGeeks
      String to be inserted: For
      String to be inserted at index: 4
      Modified String: GeeksForGeeks
      
    2. Using String.substring() method

      Approach:

      1. Get the Strings and the index.
      2. Create a new String
      3. Insert the substring from 0 to the specified (index + 1) using substring(0, index+1) method. Then insert the string to be inserted into the string. Then insert the remaining part of the original string into the new string using substring(index+1) method.
      4. Return/Print the new String

      Below is the implementation of the above approach:

      Program:

      import java.lang.*;

      class GFG {

          public static String insertString(

              String originalString,

              String stringToBeInserted,

              int index)

          {

              String newString = originalString.substring(0, index + 1)

                                 + stringToBeInserted

                                 + originalString.substring(index + 1);

              return newString;

          }

          public static void main(String[] args)

          {

              String originalString = "GeeksGeeks";

              String stringToBeInserted = "For";

              int index = 4;

              System.out.println("Original String: "

                                 + originalString);

              System.out.println("String to be inserted: "

                                 + stringToBeInserted);

              System.out.println("String to be inserted at index: "

                                 + index);

              System.out.println("Modified String: "

                                 + insertString(originalString,

                                                stringToBeInserted,

                                                index));

          }

      }

      Output:

      Original String: GeeksGeeks
      String to be inserted: For
      String to be inserted at index: 4
      Modified String: GeeksForGeeks
      
    3. Using StringBuffer.insert() method

      Approach:

      1. Get the Strings and the index.
      2. Create a new StringBuffer
      3. Insert the stringToBeInserted into the original string using StringBuffer.insert() method.
      4. Return/Print the String from the StringBuffer using StringBuffer.toString() method.

      Below is the implementation of the above approach:

      Program:

      import java.lang.*;

      class GFG {

          public static String insertString(

              String originalString,

              String stringToBeInserted,

              int index)

          {

              StringBuffer newString

                  = new StringBuffer(originalString);

              newString.insert(index + 1, stringToBeInserted);

              return newString.toString();

          }

          public static void main(String[] args)

          {

              String originalString = "GeeksGeeks";

              String stringToBeInserted = "For";

              int index = 4;

              System.out.println("Original String: "

                                 + originalString);

              System.out.println("String to be inserted: "

                                 + stringToBeInserted);

              System.out.println("String to be inserted at index: "

                                 + index);

              System.out.println("Modified String: "

                                 + insertString(originalString,

                                                stringToBeInserted,

                                                index));

          }

      }

      Output:

      Original String: GeeksGeeks
      String to be inserted: For
      String to be inserted at index: 4
      Modified String: GeeksForGeeks
      

    Last Updated :
    11 Dec, 2018

    Like Article

    Save Article

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

    1. Использование indexOf() метод

    Идея состоит в том, чтобы использовать indexOf() метод String class, который возвращает в этой строке индекс первого вхождения указанной подстроки, начиная с указанного индекса. Он возвращается -1 если такого явления нет.

    Хитрость заключается в том, чтобы начать с позиции, где заканчивается последняя найденная подстрока. Это показано ниже:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    class Main

    {

        /* Проверяет, является ли строка пустой («») или нулевой. */

        public static boolean isEmpty(String s) {

            return s == null || s.length() == 0;

        }

        /* Подсчитывает, сколько раз подстрока появляется в большей строке. */

        public static int countMatches(String text, String str)

        {

            if (isEmpty(text) || isEmpty(str)) {

                return 0;

            }

            int index = 0, count = 0;

            while (true)

            {

                index = text.indexOf(str, index);

                if (index != 1)

                {

                    count ++;

                    index += str.length();

                }

                else {

                    break;

                }

            }

            return count;

        }

        public static void main(String[] args)

        {

            String text = «AABCCAAADCBBAADBBC»;

            String str = «AA»;

            int count = countMatches(text, str);

            System.out.println(count);

        }

    }

    Скачать  Выполнить код

    результат:

    3

    2. Использование split() метод

    Хитрое решение состоит в том, чтобы использовать split() метод разделения строки вокруг заданной подстроки. Это показано ниже:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    class Main

    {

        /* Проверяет, является ли строка пустой («») или нулевой. */

        public static boolean isEmpty(String s) {

            return s == null || s.length() == 0;

        }

        /* Подсчитывает, сколько раз подстрока появляется в большей строке. */

        public static int countMatches(String text, String str)

        {

            if (isEmpty(text) || isEmpty(str)) {

                return 0;

            }

            return text.split(str, 1).length 1;

        }

        public static void main(String[] args)

        {

            String text = «AABCCAAADCBBAADBBC»;

            String str = «AA»;

            int count = countMatches(text, str);

            System.out.println(count);

        }

    }

    Скачать  Выполнить код

    результат:

    3

    3. Использование сопоставления с образцом

    Мы также можем воспользоваться помощью регулярных выражений в Java для подсчета частоты подстроки, как показано ниже:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    import java.util.regex.Matcher;

    import java.util.regex.Pattern;

    class Main

    {

        /* Проверяет, является ли строка пустой («») или нулевой. */

        public static boolean isEmpty(String s) {

            return s == null || s.length() == 0;

        }

        /* Подсчитывает, сколько раз подстрока появляется в большей строке. */

        public static int countMatches(String text, String str)

        {

            if (isEmpty(text) || isEmpty(str)) {

                return 0;

            }

            Matcher matcher = Pattern.compile(str).matcher(text);

            int count = 0;

            while (matcher.find()) {

                count++;

            }

            return count;

        }

        public static void main(String[] args)

        {

            String text = «AABCCAAADCBBAADBBC»;

            String str = «AA»;

            int count = countMatches(text, str);

            System.out.println(count);

        }

    }

    Скачать  Выполнить код

    результат:

    3

    4. Использование Apache Commons Lang

    Наконец, мы можем использовать библиотеку Apache Commons Lang, в которой countMatches() метод, включенный в StringUtils класс именно для этой цели.

    import org.apache.commons.lang3.StringUtils;

    class Main

    {

        public static void main(String[] args)

        {

            String text = «AABCCAAADCBBAADBBC»;

            String str = «AA»;

            int count = StringUtils.countMatches(text, str);

            System.out.println(count);

        }

    }

    Скачать код

    результат:

    3

    Это все, что касается поиска вхождений подстроки в строке в Java.

    В этой статье мы рассмотрим операции со строкой и подстрокой. Вы узнаете, как соединять и сравнивать строки, как извлекать символы и подстроки, как выполнять поиск в строке.

    Соединение строк в Java

    Чтобы соединить строки в Java, подойдёт операция сложения «+»:

    String str1 = "Java";
    String str2 = "Hi";
    String str3 = str1 + " " + str2;
    
    System.out.println(str3); // Hi Java
    

    Если же в предстоящей операции сложения строк будет применяться нестроковый объект, допустим, число, данный объект преобразуется к строке:

    String str3 = "Год " + 2020;
    

    По факту, когда мы складываем строки с нестроковыми объектами, вызывается метод valueOf() класса String. Этот метод преобразует к строке почти все типы данных. Чтобы преобразовать объекты разных классов, valueOf вызывает метод toString() данных классов.

    Объединять строки можно и с помощью concat():

    String str1 = "Java";
    String str2 = "Hi";
    str2 = str2.concat(str1); // HiJava
    

    Метод принимает строку, с которой нужно объединить вызывающую строку, возвращая нам уже соединённую строку.

    Также мы можем использовать метод join(), позволяющий объединять строки с учетом разделителя. Допустим, две строки выше слились в слово «HiJava», однако мы бы хотели разделить подстроки пробелом. Тут и пригодится join():

    String str1 = "Java";
    String str2 = "Hi";
    String str3 = String.join(" ", str2, str1); // Hi Java
    

    Метод join — статический. Первый параметр — это разделитель, который будет использоваться для разделения подстрок в общей строке. Последующие параметры осуществляют передачу через запятую произвольного набора объединяемых подстрок — в нашем случае их две, но можно и больше.

    Извлекаем символы и подстроки в Java

    Чтобы извлечь символы по индексу, в классе String есть метод char charAt(int index). Этот метод принимает индекс, по которому необходимо получить символы, возвращая извлеченный символ:

    String str = "Java";
    char c = str.charAt(2);
    System.out.println(c); // v
    

    Обратите внимание, что индексация начинается с нуля, впрочем, как и в массивах.
    Если же нужно извлечь сразу группу символов либо подстроку, подойдёт getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin). Этот метод принимает ряд параметров:
    • srcBegin: индекс в нашей строке, с которого осуществляется начало извлечения символов;
    • srcEnd: индекс в нашей строке, до которого осуществляется извлечение символов;
    • dst: массив символов (именно в него будут эти символы извлекаться);
    • dstBegin: индекс в массиве dst (с него надо добавлять символы, извлечённые из строки).

    String str = "Hi world!";
    int start = 6;
    int end = 11;
    char[] dst=new char[end - start];
    str.getChars(start, end, dst, 0);
    System.out.println(dst); // world
    

    Сравниваем строки в Java

    Мы уже писали о том, как сравнивать строки в Java, используя для этого метод equals() (регистр учитывается) и equalsIgnoreCase() (регистр не учитывается). Хотелось бы сказать пару слов про ещё одну пару методов: int compareTo(String str) и int compareToIgnoreCase(String str) — они позволяют не только сравнить 2 строки, но и узнать, больше ли одна другой. Если значение, которое возвращается, больше 0, первая строка больше, если меньше нуля, всё наоборот. Когда обе строки равны, вернётся ноль.

    Для определения используется лексикографический порядок. Допустим, строка «A» меньше строки «B», ведь символ ‘A’ в алфавите находится перед символом ‘B’. Когда первые символы строк равны, в расчёт берутся следующие символы. К примеру:

    String str1 = "hello";
    String str2 = "world";
    String str3 = "hell";
    
    System.out.println(str1.compareTo(str2)); // -15 - str1 меньше, чем strt2
    System.out.println(str1.compareTo(str3)); // 1 - str1 больше, чем str3
    

    Поиск в строке в Java

    Чтобы найти индекс первого вхождения подстроки в строку, используют метод indexOf(), последнего — метод lastIndexOf(). Если подстрока не найдена, оба метода вернут -1:

    String str = "Hello world";
    int index1 = str.indexOf('l'); // 2
    int index2 = str.indexOf("wo"); //6
    int index3 = str.lastIndexOf('l'); //9
    

    Чтобы определить, начинается строка с определённой подстроки, применяют метод startsWith(). Что касается метода endsWith(), то он даёт возможность определить оканчивается ли строка на определенную подстроку:

    String str = "myfile.exe";
    boolean start = str.startsWith("my"); //true
    boolean end = str.endsWith("exe"); //true
    

    Выполняем замену в строке в Java

    Заменить в нашей строке одну последовательность символов другой можно с помощью метода replace():

    String str = "Hello world";
    String replStr1 = str.replace('l', 'd'); // Heddo wordd
    String replStr2 = str.replace("Hello", "Bye"); // Bye world
    

    Обрезаем строки в Java

    Для удаления начальных и конечных пробелов применяют метод trim():

    String str = "  hello world  ";
    str = str.trim(); // hello world 
    

    Также существует метод substring() — он возвращает подстроку, делая это с какого-нибудь конкретного индекса до конца либо до определённого индекса:

    String str = "Hello world";
    String substr1 = str.substring(6); // world
    String substr2 = str.substring(3,5); //lo
    

    Меняем регистр в Java

    При необходимости вы можете перевести все символы вашей строки в нижний регистр (toLowerCase()) или в верхний (toUpperCase()):

    String str = "Hello World"; 
    System.out.println(str.toLowerCase()); // hello world
    System.out.println(str.toUpperCase()); // HELLO WORLD
    

    Split

    С помощью этого метода вы сможете разбить строку на подстроки по конкретному разделителю. Под разделителем понимается какой-либо символ либо набор символов, передаваемые в метод в качестве параметра. Давайте для примера разобьём небольшой текст на отдельные слова:

    String text = "OTUS is a good company";
    String[] words = text.split(" ");
    for(String word : words){
        System.out.println(word);
    }
    

    В нашем случае строка разделится по пробелу, и мы получим следующий консольный вывод:

    
    

    Вот и всё! Узнать больше всегда можно на наших курсах:
    Java_970x90-20219-db8529.png

    При написании статьи использовались материалы:
    1. «Java-примеры: найти последнее вхождение подстроки в строке».
    2. «Основные операции со строками».

    A quick explanation for Java program to Insert a String into another String. Writing program in 3 ways using normal approach, String API and StringBuffer API.

    1. Overview

    We’ll demonstrate how to add a string into another string at any given position in java.

    We will write implementation in 3 ways which iterate through the string till given position and then add new string, finally add the remaining original string.

    As we know String class is immutable in java. Any operation on string will result a new String.

    Insert a String into another String

    First, We will see a few example input and outputs.

    Example 1:

    Input: OriginalStringValue = "java blog"
        newStringToBeinserted = " w3schools"
        position = 4
    
    Output: java w3schools blog
    

    Example 2:

    Example 2:

    Input: OriginalStringValue = "first last"
        newStringToBeinserted = " middle"
        position = 5
    
    Output: first middle last
    

    We further in this article will discuss on simple approach, using substring method and StringBuffer api.

    2. Simple Approach

    In this program, We will be using very simple and straight forward approach to solve the problem. Explained step by step below.

    2.1 Steps:

    a) Initiate startIndex = 0 and endIndex to originalString.length
    b) Create a newString with empty content.
    c) Iterate the loop through originalString string from originalString to endIndex .
    d) Take char by char and add it to newString. Increment startIndex by 1 for each character.
    e) If startIndex is equal to position then append the toBeInserted string to the newString.
    f) Add rest of the characters to newString.
    g) return newString.

    2.2 Program

    Let us have a look at the following program using substring method.

    /**
     * Insert a String into another String in Java using normal approach
     * 
     * @param originalString
     * @param position
     * @param toBeInserted
     * @return
     */
    public String insertStringAtPosition(String originalString, int position, String toBeInserted) {
    
      int startIndex = 0;
      int endIndex = originalString.length();
      String newString = "";
    
      for (int i = startIndex; i < endIndex; i++) {
      // Insert the original string character into the new string
      newString += originalString.charAt(startIndex);
    
      if (startIndex == position) {
       // Insert the string to be inserted into the new string
       newString += toBeInserted;
      }
     }
    
     return newString;
    }
    

    3. Using String class substring

    String class has a method called substring that returns a part of string for the any given from and to indexes. substring method is overloaded in String class as follows.

    substring (int beginIndex): Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

    substring​(int beginIndex, int endIndex): Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex — 1. Thus the length of the substring is endIndex-beginIndex.

    Note: Always substring method ignores endIndex. Considers 0 to endIndex-1 as substring.

    3.1 Steps:

    a) Taking three string variables named «first», «middle» and «last«.
    b) Take substring from originalString from index o to position + 1. Store in «first» string variable.
    c) Next store toBeInserted value into «middle» string variable.
    d) Take substring from originalString from index position + 1 to it’s length.
    e) Now concatenating these three strings will give us the final output.

    3.2 Program

    Let us have a look at the following program using substring method.

    /**
     * Insert a String into another String in Java using String class substring
     * method.
     * 
     * @param originalString
     * @param position
     * @param toBeInserted
     * @return
     */
    public String insertStringAtPositionUsingSubString(String originalString, int position,
      String toBeInserted) {
    
     String first = originalString.substring(0, position + 1);
     String middle = toBeInserted;
     String last = originalString.substring(position + 1, originalString.length());
     
     String newString = first + middle + last;
    
     return newString;
    }
    

    4. StringBuffer insert() method

    StringBuffer has a method insert() which takes index and string to be inserted. This method will insert the given string at the given position. All rest of the characters right side to it will be shifted to right.

    4.1 Steps

    a) Create a new StringBuffer instance passing originalString.
    b) Call StringBuffer insert method passing index «position + 1″ and string toBeInserted.
    c) Convert StringBuffer to String by invoking toString() method. This is will be the our output newString.

    4.2 Program

    Let us have a look at the following program using StringBuffer insert method with offset and string toBeInserted.

    /**
     * Insert a String into another String in Java using StringBuffer class insert
     * method.insert method takes offset value which is the index where the new
     * string to be inserted and the string toBeInserted.
     * 
     * @param originalString
     * @param position
     * @param toBeInserted
     * @return
     */
    public static String insertStringAtPositionUsingStringBuffer(String originalString, int position,
      String toBeInserted) {
    
     StringBuffer buffer = new StringBuffer(originalString);
     buffer.insert(position + 1, toBeInserted);
     String newString = buffer.toString();
    
     return newString;
    }
    

    5. Conclusion

    In this article, We’ve discussed about inserting a string into another string using common approcach, stirng substring method and StringBuffer.insert() method.

    But, performance wise first approach is a bit time consuming time. substring and insert method does good in performance because these are builtin api methods which are tested by millions lines of code in production.

    All code shown in this tutorial are on GitHub.

    Понравилась статья? Поделить с друзьями:
  • Как найти номер телефона генерального директора
  • Как составить пояснительную записку к балансу для фсс образец
  • Как найти корень с чередованием гласных
  • Как можно исправить прикус если есть коронки
  • Симс 4 как найти умершего персонажа