Java android string contains

Java — String contains() Method

The Java String contains() method is used to check whether the current string contains the specified sequence. It returns the Boolean value, which is true if and only if the string contains the sequence of char values; false otherwise.

The contains () method accepts a character sequence as an argument. It throws an exception if one of the sequence contains null value. A char sequence is readable sequence of the character values.

Syntax

Following is the syntax of the Java String contains() method −

public boolean contains(CharSequence s)

Parameters

Return Value

This method returns true if this string contains s, else false.

Example

If the given string value contains the specified character sequence value, the contains() method returns true.

In the following program, we are instantiating the string class with the value “Java Programming”. Then, we are creating the char sequence with the value “Java”. Using the contains() method, we are trying to check whether the given string contains the specified char sequence or not.

import java.lang.*; public class Concat < public static void main(String[] args) < //instantiate the string class String str1 = new String("Java Programming"); System.out.println("The given string: " + str1); //initialize the char sequence CharSequence str2 = "Java"; System.out.println("The given char sequence is: " + str2); //using the contains() method boolean bool = str1.contains(str2); System.out.println("The string contains the specified char sequence or not? " + bool); >>

Output

On executing the above program, it will produce the following result −

The given string: Java Programming The given char sequence is: Java The string contains the specified char sequence or not? true

Example

If the given string value does not contain the specified character sequence value, the contains () method returns false.

In the following program, we are creating an object the string class with the value “HelloWorld”. Then, we are creating the char sequence with the value “helo”. Using the contains() method, we are trying to check whether the given string contains the specified char sequence or not.

import java.lang.*; public class Concat < public static void main(String[] args) < // creating an object the string class String str1 = new String("HelloWorld"); System.out.println("The given string: " + str1); //initialize the char sequence CharSequence str2 = "helo"; System.out.println("The given char sequence is: " + str2); //using the contains() method boolean bool = str1.contains(str2); System.out.println("The string contains the specified char sequence or not? " + bool); >>

Output

Following is the output of the above program −

The given string: HelloWorld The given char sequence is: helo The string contains the specified char sequence or not? false

Example

If the given char sequence value is null, this method throws a NullPointerException.

In this program, we are creating a string literal with the value “hello”. Then, we are creating a char sequence with the null value. Using the contains() method, we are trying to check whether the given string contains the specified char sequence null or not.

import javalang.*; public class Concat < public static void main(String[] args) < try < // instantiate the string class String str1 = "hello"; System.out.println("The given string: " + str1); CharSequence str2 = null; System.out.println("The given char sequence is: " + str2); //using the contains() method boolean bool = str1.contains(str2); System.out.println("The string conatins the specified char seqience or not? " + bool); >catch(NullPointerException e) < e.printStackTrace(); System.out.println("Exception: " + e); >> >

Output

The above program, produces the following output −

The given string: hello The given char sequence is: null java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.toString()" because "s" is null at java.base/java.lang.String.contains(String.java:2854) at com.tutorialspoint.StringBuilder.Concat.main(Concat.java:11) Exception: java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.toString()" because "s" is null

Example

If the given string and char sequence value is the same, but the cases are different, the contains() method return false.

Читайте также:  Максимальная длина имени переменной python

In this example, we are instantiating the string class with the value “TUTORIX”. Then, we are creating the char sequence with the value “tutorix”. Using the contains() method, we are trying to compare whether the string contains the specified char sequence or not.

package com.tutorialspoint.String; import java.lang.*; public class Concat < public static void main(String[] args) < // instantiate the string class String str1 = new String("TUTORIX"); System.out.println("The given string: " + str1); CharSequence str2 = "tutorix"; System.out.println("The given char sequence is: " + str2); //using the contains() method boolean bool = str1.contains(str2); System.out.println("The contains() method return: " + bool); if(bool) < System.out.println("The given string contains the spcified char sequence"); >else < System.out.println("The given string does not contain the specified char sequence"); >> >

Output

After executing the above program, it generates the following output −

The given string: TUTORIX The given char sequence is: tutorix The contains () method return: false The given string does not contain the specified char sequence

Источник

In Java, how do I check if a string contains a substring (ignoring case)? [duplicate]

I have two String s, str1 and str2 . How do I check if str2 is contained within str1 , ignoring case?

Both indexOf and contains go character by character, so if you need faster string searching (which you can get), then you would need to implement one of many published algorithms.

6 Answers 6

str1.toUpperCase().contains(str2.toUpperCase()) 

Original answer was using toLowerCase() method. But as some people correctly noticed, there are some exceptions in Unicode and it’s better to use toUpperCase() . Because:

There are languages knowing more than one lower case variant for one upper case variant.

@RadijatoR yes, it’s called indexOf, like int pos = str1.indexOf(str2) or case insensitive as int pos = str1.toLowerCase().indexOf(str2.toLowerCase())

String string = "Madam, I am Adam"; // Starts with boolean b = string.startsWith("Mad"); // true // Ends with b = string.endsWith("dam"); // true // Anywhere b = string.indexOf("I am") >= 0; // true // To ignore case, regular expressions must be used // Starts with b = string.matches("(?i)mad.*"); // Ends with b = string.matches("(?i).*adam"); // Anywhere b = string.matches("(?i).*i am.*"); 

Your «indexOf» example should use >= 0, not > 0, since 0 is valid if the substring occurs at the beginning of the string. (Doesn’t in your example, but could in other cases.) Added this response since people are obviously still searching and finding this answer.

Читайте также:  METANIT.COM

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

String container = "aBcDeFg"; String content = "dE"; boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content); 

You can use the toLowerCase() method:

public boolean contains( String haystack, String needle ) < haystack = haystack == null ? "" : haystack; needle = needle == null ? "" : needle; // Works, but is not the best. //return haystack.toLowerCase().indexOf( needle.toLowerCase() ) >-1 return haystack.toLowerCase().contains( needle.toLowerCase() ) > 

Notice that by creating your own method, you can reuse it. Then, when someone points out that you should use contains instead of indexOf , you have only a single line of code to change.

I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for «Need$le» cold be problematic).

Building on some of the above examples:

public boolean containsIgnoreCase( String haystack, String needle ) < if(needle.equals("")) return true; if(haystack == null || needle == null || haystack .equals("")) return false; Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL); Matcher m = p.matcher(haystack); return m.find(); >example call: String needle = "Need$le"; String haystack = "This is a haystack that might have a need$le in it."; if( containsIgnoreCase( haystack, needle) )

(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)

Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning «true» if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning «false» if a position > haystack.length() — needle.length() is reached.

Источник

To check if string contains particular word

Thank you for the answer fthopkins. Its an old question, but i faced a similar situation today at work. The above code searches for charsequence not the word. For example:- If we want to catch only «keyword» and not any extensions like «keyword_1″, the above code will not work. One way to avoid this can be to search with String contains function for » keyword » (note the two blank spaces on either side ) — is there a more elegant way to do it?

@JavaTec you’ll need to use a regex to search for words properly. Similar to m0skit0’s answer (and see that answer for using compiled expressions if you use the same expression over and over), you’ll want to do this: if (d.matches(«\\bkeyword\\b»)) . \b ( \\b in a string to escape the backslash) matches a «word boundary», i.e. the edges of a word. The advantage over using blank spaces is it will properly match things like «sentence with a keyword.» (full stop instead of space) or even «keyword» (no space at beginning or end).

Читайте также:  Main cpp hello world

This code only checks if a string contains another string. The semantics don’t hold for actual words. cheese != cheeseburger and cat != catalogue.

.contains() is perfectly valid and a good way to check.

Since you didn’t post the error, I guess d is either null or you are getting the «Cannot refer to a non-final variable inside an inner class defined in a different method» error.

To make sure it’s not null, first check for null in the if statement. If it’s the other error, make sure d is declared as final or is a member variable of your class. Ditto for c .

You can use regular expressions:

.* -> 0 or more of any characters

If you will be checking this often, it is better to compile the regular expression in a Pattern object and reuse the Pattern instance to do the checking.

private static final Pattern HEYPATTERN = Pattern.compile(".*Hey.*"); [. ] if (HEYPATTERN.matcher(d).matches()) < c.setText("OUTPUT: SUCCESS!"); >else

Just note this will also match «Heyburg» for example since you didn’t specify you’re searching for «Hey» as an independent word. If you only want to match Hey as a word, you need to change the regex to .*\\bHey\\b.*

@m0skit0 can we do this matching by ignoring the case, i.e. i want to match if a sentence contains android/Android it should return true.

The other answer (to date) appear to check for substrings rather than words. Major difference.

With the help of this article, I have created this simple method:

static boolean containsWord(String mainString, String word) < Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE); // "\\b" represents any word boundary. Matcher matcher = pattern.matcher(mainString); return matcher.find(); >

Solution-1: — If you want to search for a combination of characters or an independent word from a sentence.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful." if (sentence.matches(".*Beneficent.*")) else

Solution-2: — There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful." if (sentence.matches(".* cent .*")) else

Now in Solution-2 it wll return false because no independent cent word exist.

Additional: You can add or remove space on either side in 2nd solution according to your requirements.

Источник

Оцените статью