Как проверить наличие символа в строке java
Перейти к содержимому

Как проверить наличие символа в строке java

  • автор:

Как проверить содержит ли строка символ java

Аватар пользователя Иван Полежаев

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

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

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

Java: Check if String Contains a Substring

Checking for substrings within a String is a fairly common task in programming. For example, sometimes we wish to break a String if it contains a delimiter at a point. Other times, we wish to alter the flow if a String contains (or lacks) a certain substring, which could be a command.

There's a couple of ways to do this in Java, and most of them are what you'd expect to see in other programming languages as well. One approach that is unique to Java, however, is the use of a Pattern class, which we'll cover later in the article.

Alternatively, you can use Apache Commons and the helper class StringUtils , which offers many derived methods from the core methods for this purpose.

Core Java

String.contains()

The first and foremost way to check for the presence of a substring is the .contains() method. It's provided by the String class itself and is very efficient.

The method accepts a CharSequence and returns true if the sequence is present in the String we call the method on:

Running this would yield:

Note: The .contains() method is case sensitive. If we tried looking for "Va" in our string , the result would be false .

Oftentimes, to avoid this issue, since we're not looking for case sensitivity, you'd match the case of both Strings before checking:

String.indexOf()

The .indexOf() method is a bit more crude than the .contains() method, but it's nevertheless the underlying mechanism that enables the .contains() method to work.

It returns the index of the first occurrence of a substring within a String, and offers a few constructors to choose from:

We can either search for a single character with or without an offset or search for a String with or without an offset.

The method will return the index of the first occurrence if present, and -1 if not:

Running this code will yield:

  • The first occurrence of i is in the word ipsum , 6 places from the start of the character sequence.
  • The first occurrence of i with an offset of 8 (i.e. the search starts at s of ipsum ) is in the sit word, 19 places from the start.
  • The first occurrence of the String dolor is 12 places from the start.
  • And finally, there is no occurrence of Lorem with an offset of 10 .

Ultimately, the .contains() method calls upon the .indexOf() method to work. That makes .indexOf() inherently even more efficient than the counterpart (albeit a very small amount) — though it does have a slightly different use-case.

String.lastIndexOf()

As opposed to the .indexOf() method, which returns the first occurrence, the .lastIndexOf() method returns the index of the last occurrence of a character or String, with or without an offset:

Running this code will yield:

Some may be a bit surprised by the results and say:

lastIndexOf('i', 8) should've returned 19 as that's the last occurrence of the character after the 8th character in the String

What's worth noting is that when running the .lastIndexOf() method, the character sequence is reversed. The counting starts at the final character and goes towards the first.

That being said — yes. The expected output is 6 , as that's the last occurrence of the character after skipping 8 elements from the end of the sequence.

Pattern with Regex and Matcher

The Pattern class is essentially a compiled representation of a regular expression. It's used alongside the Matcher class to match character sequences.

This class works by compiling a pattern first. We then assign another pattern to a Matcher instance, which uses the .find() method to compare the assigned and compiled patterns.

If they match, the .find() method results in true . If the patterns don't match, the method results in false .

This would yield:

Apache Commons

Due to its usefulness and prevalence in Java, many projects have Apache Commons included in the classpath. It's a great library with many useful features often used in production — and checking for substrings is no exception.

Apache Commons offers the StringUtils class with many helper methods for String manipulation, null-checking, etc. For this task, we can utilize any of the .contains() , .indexOf() , .lastIndexOf() , or .containsIgnoreCase() methods.

If not, including it is as easy as adding a dependency to your pom.xml file if you're using Maven:

Or by adding it through Gradle:

StringUtils.contains()

The .contains() method is pretty straightforward and very similar to the core Java approach.

The only difference is that we don't call the method on the String we're checking (as it doesn't inherit this method), but rather pass the String we're searching in alongside the String we're searching for:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Running this code will yield:

Note: This method is case-sensitive.

StringUtils.indexOf()

Naturally, the .indexOf() method also works very similarly to the core Java approach:

Running this code will yield:

StringUtils.indexOfAny()

The .indexOfAny() method accepts a vararg of characters, instead of a single one, allowing us to search for the first occurrence of any of the passed characters:

Running this code will yield:

StringUtils.indexOfAnyBut()

The .indexOfAnyBut() method searches for the first occurrence of any character that's not in the provided set:

Running this code will yield:

StringUtils.indexOfDifference()

The .indexOfDifference() method compares two character arrays, and returns the index of the first differing character:

Running this code will yield:

StringUtils.indexOfIgnoreCase()

The .indexOfIgnoreCase() method will return the index of the first occurrence of a character in a character sequence, ignoring its case:

Running this code will yield:

StringUtils.lastIndexOf()

And finally, the .lastIndexOf() method works pretty much the same as the regular core Java method:

Running this code will yield:

StringUtils.containsIgnoreCase()

The .containsIgnoreCase() method checks if String contains a substring, ignoring the case:

Running this code will yield:

StringUtils.containsOnly()

The .containsOnly() method checks if a character sequence contains only the specifies values.

This can be a bit misleading, so another way to put it is — it checks if the character sequence is made up of only the specified characters. It accepts either a String or a character sequence:

Running this will yield:

The "Hello World!" String indeed is constructed of only the characters in the 'HleWord!' sequence.

Note: Not all of the characters from the sequence need to be used in the string for the method to return true. What matters is that string doesn't contain a character that's not in the character sequence.

StringUtils.containsNone()

The .containsNone() method checks if the String contains any of the "forbidden" characters from a set. If it does, false is returned, and vice-versa:

Running this code yields:

StringUtils.containsAny()

And finally, the .containsAny() method returns true if a character sequence contains any of the passed parameters in the form of a character sequence or a String:

This code would yield:

Conclusion

In conclusion, there are many ways to check for a substring in a String. The core Java approach will be enough in most cases, though if you need to check with more than a single condition — Apache Commons is a real time-saver.

In many cases, defining logic of your own for a method such as .indexOfAnyBut() would be a pain and simply redundant. Since most projects nowadays already have Apache Commons in the classpath, it's most likely that you can simply use the methods provided by the StringUtils class.

Ищем символы в строке Java

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

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

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

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

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

Метод indexOf()

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

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

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

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

Метод contains

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

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

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

How can I check if a single character appears in a string?

barfoon's user avatar

it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

    which checks if the string contains a specified sequence of char values which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)

I’m not sure what the original poster is asking exactly. Since indexOf(. ) and contains(. ) both probably use loops internally, perhaps he’s looking to see if this is possible at all without a loop? I can think of two ways off hand, one would of course be recurrsion:

The other is far less elegant, but completeness.

The number of lines grow as you need to support longer and longer strings of course. But there are no loops/recurrsions at all. You can even remove the length check if you’re concerned that that length() uses a loop.

You can use 2 methods from the String class.

    which checks if the string contains a specified sequence of char values which returns the index within the string of the first occurence of the specified character or substring or returns -1 if the character is not found (there are 4 variations of this method)

If you need to check the same string often you can calculate the character occurrences up-front. This is an implementation that uses a bit array contained into a long array:

To check if something does not exist in a string, you at least need to look at each character in a string. So even if you don’t explicitly use a loop, it’ll have the same efficiency. That being said, you can try using str.contains(«»+char).

Is the below what you were looking for?

Yes, using the indexOf() method on the string class. See the API documentation for this method

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

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

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.

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *