Как найти char в string

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

A Quick overview to how to check char or String is in string in java using various methods.

1. Overview

In this tutorial, We will check the possible ways to check the given char or string in the given string. If the char is present then need to return it’s index.

Throughout this post, we will be writing the examples on below string.

Check Char Is In String

String string = "find string";

indexof() and lastIndexOf methods return int value as index of the found character.

Please go through the previous post, how String contains() method works in java with examples. This post will give you understanding how indexof method is used internally.

2.1 indexOf​(int ch)

indexof method is present in java.lang.String package which takes char as method argument and returns int which is the index of the matched chat if found.

Simple words, This method returns the index within this string of the first occurrence of the specified character.

int index = string.indexOf('d');
System.out.println("index for chat d: " + index);

Output:

index for char d: 3

Even though if char ‘d’ appears multiple time also, it returns first match.

Internally, indexOf method runs the for loop from string index 1 to its length and check every character with the given character by invoking charAt() method.

this.charAt(k) == ch

where k is index from for loop.

If it finds the given char then return its index. If not, returns -1.

int index = string.indexOf('z');

Output:

index for char z: -1

2.2 indexOf​(int ch, int fromIndex)

This method works similar to the above method but it starts search from given fromIndex.

From string api “Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.”

index = string.indexOf('i', 4);

Output:

index for char d: 8

Searching char ‘i’ starts from index 4.

Note: indexof(char c) internally calls indexOf​(int ch, int fromIndex) method as indexOf​(ch, 0).

3. lastIndexOf​

3.1 lastIndexOf​(int ch)

lastIndexOf​ method searches the char from index 0 to length-1. But this returns the last match and returns it’s index. This method also internally uses charAt method.

this.charAt(k) == ch

In input string “find string”, char ‘i’ is present two times at index 1 and 8. Now, we’ll call lastIndexOf​ method and output should the 8 for char ‘i’. See the below code.

index = string.lastIndexOf('i');
System.out.println("last index for char i: " + index);

Output:

last index for char i: 8

If no char finds then returns ‘-1’.

This method works internally search backwards starting index from length-1 to zero.

3.2 lastIndexOf​(int ch, int fromIndex)

This method returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

Internal condition:

(this.charAt(k) == ch) && (k <= fromIndex)

Now, we will pass fromIndex as ‘3’ then it will start searching backward from index 3 to 0.

index = string.lastIndexOf('i', 3); 
System.out.println("last index for char i: " + index);

Output:

last index for char i: 1

4 indexOf​(String str)

We’ll use the below string in examples from this point.

String newString = "hello java, welcome to java w3schools blog";

4.1 indexOf​(String str)

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

index = newString.indexOf("java");
System.out.println("string "java" index found at: " + index);

Output:

string "java" index found at: 6

Internally, this method calls this.startsWith(str, k) method.

4.2 indexOf​(String str, int fromIndex)

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

index = newString.indexOf("java", 9);
System.out.println("string "str" index found at: " + index);

Output:

string "java" index found at: 23

In the above example, seaching will start from index 9. It ignores the match at index 5 and take match from index 23.

Internally, this method calls below code.

k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k)

4.3 lastIndexOf​(String str)

Returns the index within this string of the last occurrence of the specified substring. The last occurrence of the empty string “” is considered to occur at the index value this.length().

index = newString.lastIndexOf("java");
System.out.println("string "str" index found at: " + index);

Output: 

lastIndexOf: string "str" index found at: 23

4.4 lastIndexOf​(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

index = newString.lastIndexOf("java", 9);
System.out.println("lastIndexOf: string "str" index found at: " + index); 

Output:

lastIndexOf: string "str" index found at: 6

5. Conclusion

In this article, we’ve seen how to find the char is present in the string using string api methods such as indexOf, lastIndexOf methods.
Finally, if index is negetive then it will return value ‘-1’.
indexOf method is used internally in contains(), replace(), split(), isBlank(), indent() methods.

All examples shown in this post are available on GitHub.

String.contains(String) or String.indexOf(String) – suggested

"abc".contains("Z"); // false - correct
"zzzz".contains("Z"); // false - correct
"Z".contains("Z"); // true - correct
"😀and😀".contains("😀"); // true - correct
"😀and😀".contains("😂"); // false - correct
"😀and😀".indexOf("😀"); // 0 - correct
"😀and😀".indexOf("😂"); // -1 - correct

String.indexOf(int) and carefully considered String.indexOf(char) with char to int widening

"😀and😀".indexOf("😀".charAt(0)); // 0 though incorrect usage has correct output due to portion of correct data
"😀and😀".indexOf("😂".charAt(0)); // 0 -- incorrect usage and ambiguous result
"😀and😀".indexOf("😂".codePointAt(0)); // -1 -- correct usage and correct output

The discussions around character is ambiguous in Java world

can the value of char or Character considered as single character?

No. In the context of unicode characters, char or Character can sometimes be part of a single character and should not be treated as a complete single character logically.

if not, what should be considered as single character (logically)?

Any system supporting character encodings for Unicode characters should consider unicode’s codepoint as single character.

So Java should do that very clear & loud rather than exposing too much of internal implementation details to users.

String class is bad at abstraction (though it requires confusingly good amount of understanding of its encapsulations to understand the abstraction 😒😒😒 and hence an anti-pattern).

How is it different from general char usage?

char can be only be mapped to a character in Basic Multilingual Plane.

Only codePoint - int can cover the complete range of Unicode characters.

Why is this difference?

char is internally treated as 16-bit unsigned value and could not represent all the unicode characters using UTF-16 internal representation using only 2-bytes. Sometimes, values in a 16-bit range have to be combined with another 16-bit value to correctly define character.

Without getting too verbose, the usage of indexOf, charAt, length and such methods should be more explicit. Sincerely hoping Java will add new UnicodeString and UnicodeCharacter classes with clearly defined abstractions.

Reason to prefer contains and not indexOf(int)

  1. Practically there are many code flows that treat a logical character as char in java.
  2. In Unicode context, char is not sufficient
  3. Though the indexOf takes in an int, char to int conversion masks this from the user and user might do something like str.indexOf(someotherstr.charAt(0))(unless the user is aware of the exact context)
  4. So, treating everything as CharSequence (aka String) is better
    public static void main(String[] args) {
        System.out.println("😀and😀".indexOf("😀".charAt(0))); // 0 though incorrect usage has correct output due to portion of correct data
        System.out.println("😀and😀".indexOf("😂".charAt(0))); // 0 -- incorrect usage and ambiguous result
        System.out.println("😀and😀".indexOf("😂".codePointAt(0))); // -1 -- correct usage and correct output
        System.out.println("😀and😀".contains("😀")); // true - correct
        System.out.println("😀and😀".contains("😂")); // false - correct
    }

Semantics

  1. char can handle most of the practical use cases. Still its better to use codepoints within programming environment for future extensibility.
  2. codepoint should handle nearly all of the technical use cases around encodings.
  3. Still, Grapheme Clusters falls out of the scope of codepoint level of abstraction.
  4. Storage layers can choose char interface if ints are too costly(doubled). Unless storage cost is the only metric, its still better to use codepoint. Also, its better to treat storage as byte and delegate semantics to business logic built around storage.
  5. Semantics can be abstracted at multiple levels. codepoint should become lowest level of interface and other semantics can be built around codepoint in runtime environment.

Теги: 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

В этом посте мы обсудим, как найти индекс символа в строке на C++.

1. Использование string::find

The string::find функция-член возвращает индекс первого вхождения указанного символа в строку или string::npos если персонаж не найден. В следующем примере показан вызов этой функции:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#include <iostream>

#include <string>

int main()

{

    std::string s = “C++20”;

    char c = ‘+’;

    int index = s.find(c);

    if (index != std::string::npos) {

        std::cout << “Character found at index “ << index << std::endl;

    } else {

        std::cout << “Character not found” << std::endl;

    }

    return 0;

}

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

результат:

Character found at index 1

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#include <iostream>

#include <string>

#include <algorithm>

int main()

{

    std::string s = “C++20”;

    char c = ‘+’;

    auto it = std::find(s.begin(), s.end(), ‘+’);

    if (it != s.end()) {

        int index = std::distance(s.begin(), it);

        std::cout << “Character found at index “ << index << std::endl;

    } else {

        std::cout << “Character not found” << std::endl;

    }

    return 0;

}

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

результат:

Character found at index 1

2. Использование std::string_view

C++17 позволяет формировать строковое представление символьного литерала, используя std::literals::string_view_literals::operator””sv, заявлено в шапке <string_view>. Получив строковое представление, мы можем использовать find() функция, чтобы получить позицию первого символа данной последовательности символов, или std::string::npos если он не найден. Например,

#include <iostream>

#include <string_view>

using namespace std::string_view_literals;

int main()

{

    size_t index = “C++20”sv.find(‘+’);

    if (index != std::string::npos) {

        std::cout << “Character found at index “ << index << std::endl;

    } else {

        std::cout << “Character not found” << std::endl;

    }

    return 0;

}

Скачать код

результат:

Character found at index 1

Вот и все, что касается поиска индекса символа в строке в C++.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

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