You can use string.indexOf('a').
If the char a is present in string :
Answer from mP. on Stack Overflowit 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.
You can use string.indexOf('a').
If the char a is present in string :
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.
String.contains()which checks if the string contains a specified sequence of char valuesString.indexOf()which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
You could do something like:
String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
String two = "ROLENOMINATIONS ROLEAWARDS ROLEMOVIES";
String oneArray[] = one.split("\\s+");
String twoArray[] = one.split("\\s+");
Arrays.sort(oneArray);
Arrays.sort(twoArray);
if(Arrays.equals(oneArray, twoArray))
{
System.out.println("Contains");
}
else
System.out.println("Doesn't Contain");
}
That's because you're comparing the whole String, and apparently you seem to be thinking it checks every substring split at the space which honestly doesn't work that way (it would be unintuitive too).
So,
String one= "ROLEAWARDS ROLEMOVIES ROLENOMINATIONS";
String two = "ROLENOMINATIONS ROLEAWARDS ROLEMOVIES";
String[] oneSplit = one.split(" ");
String[] twoSplit = two.split(" ");
boolean contains = false;
for(int i = 0; i < oneSplit.length; i++)
{
for(int j = 0; j < twoSplit.length; j++)
{
if(oneSplit[i].contains(twoSplit[j])
{
contains = true;
break;
}
}
}
if(contains)
{
System.out.println("Contains");
}
else
{
System.out.println("Doesn't Contain");
}
I might use String#matches() here, with a regex alternation:
String input = "cpr1210";
if (input.matches("(?i).*(?:cpr|cvr|nr).*")) {
System.out.println("MATCH");
}
If you really wanted to use String#contains(), then you would need to have three separate calls to that method, for each sequence.
As mentioned in my comment to your question, you may use String#contains().
String testString = "cor1210";
// will not print yes, because none of the sequences fit
if (testString.contains("cpr") || testString.contains("cvr") || testString.contains("nr")) {
System.out.println("yes");
}
Make sure your logic-syntax in the if-clause is correct.
You can look at the source:
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
I'm wondering to know if there is better solution for it?
There are lots of algorithms for simple string searching; see the Wikipedia String Search page. The page includes complexity characterizations ... and references.
The standard Java java.lang.String implementation uses naive search under the hood. Some of the algorithms on the Wikipedia page that have better complexity for the search phase, but require non-trivial setup. I expect that the Sun/Oracle engineers have done extensive empirical testing and found that naive search works best on average over a wide range of real-world applications.
Finally ...
I know the brute force approach with the time complexity of
O(n*m)
In fact, that is the worst case complexity. The average complexity is O(n). Consider this:
boolean bruteForceMatch (String str1, String str2) {
for (int i = 0; i < str.length(); i++) {
boolean matches = true;
for (int j = 0; j < str2.length(); j++) {
if (i + j >= str.length ||
str1.charAt(i + j) != str2.charAt(j)) {
matched = false;
break;
}
}
if (matched) {
return true;
}
}
return false;
}
The worst case happens with inputs like "AAA..." and "AAA...B". (The dots denote repetition.)
But in the average case (e.g. randomly generated input strings) you won't have an "almost match" for str2 at every position of str1. The inner loop will typically break in the iteration.
use regular expression in java to check using str.matches(regex_here)
regex in java
for example:
if("asdhAkldffl".matches(".*[ABCDEFGH].*"))
{
System.out.println("yes");
}
The cleanest way to implement this is using StringUtils.containsAny(String, String)
package com.sandbox;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SandboxTest {
@Test
public void testQuestionInput() {
assertTrue(StringUtils.containsAny("39823839A983923", "ABCDEFGH"));
assertTrue(StringUtils.containsAny("A", "ABCDEFGH"));
assertTrue(StringUtils.containsAny("ABCDEFGH", "ABCDEFGH"));
assertTrue(StringUtils.containsAny("AB", "ABCDEFGH"));
assertFalse(StringUtils.containsAny("39823839983923", "ABCDEFGH"));
assertFalse(StringUtils.containsAny("", "ABCDEFGH"));
}
}
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
str1.toUpperCase().contains(str2.toUpperCase())
UPD:
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.
How about matches()?
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.*");
I propose the following, null-safe alternative:
Optional.ofNullable(fullString)
.orElse("")
.contains(testStr);
Ideone.com demo
When fullStr is in fact null then "" will be used, and .contains(...) will almost always1 evaluate to false.
If we want to always return false when fullStr is null, we can use:
Optional.ofNullable(fullString)
.map(s -> s.contains(testStr))
.orElse(false);
Ideone.com demo
Note that this solution will return false when both fullString and testStr are null. I know that testStr is guaranteed to be != null, but thought it might be worth mentioning.
1It will evaluate to true when testStr is "" as well
fullstring.contains(testStr)
To avoid NullPointerExceptions, use an if statement and && operator:
if (fullstring != null && fullstring.contains(testStr)) {
// your logic
}
If fullstring is null, the second part won't execute.
Edit: I thought null was falsy.
EDIT: Here is an update using the Java 8 Streaming API. So much cleaner. Can still be combined with regular expressions too.
public static boolean stringContainsItemFromList(String inputStr, String[] items) {
return Arrays.stream(items).anyMatch(inputStr::contains);
}
Also, if we change the input type to a List instead of an array we can use items.stream().anyMatch(inputStr::contains).
You can also use .filter(inputStr::contains).findAny() if you wish to return the matching string.
Important: the above code can be done using parallelStream() but most of the time this will actually hinder performance. See this question for more details on parallel streaming.
Original slightly dated answer:
Here is a (VERY BASIC) static method. Note that it is case sensitive on the comparison strings. A primitive way to make it case insensitive would be to call toLowerCase() or toUpperCase() on both the input and test strings.
If you need to do anything more complicated than this, I would recommend looking at the Pattern and Matcher classes and learning how to do some regular expressions. Once you understand those, you can use those classes or the String.matches() helper method.
public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
return true;
}
}
return false;
}
import org.apache.commons.lang.StringUtils;
String Utils
Use:
StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})
It will return the index of the string found or -1 if none is found.