Brisi
Brisi

Reputation: 1821

How to search for words starting with or contained within a certain word

I am trying to see if foo contains "inactive" or if the user is trying to type portions of the word "inactive".

Is there a simpler way to achieve this?

if (foo.equals("inactive") || foo.equals("inactiv")
                || foo.equals("inacti") || foo.equals("inact")
                || foo.equals("inac") || fofoo.equals("ina")
                || foo.equals("in") || foo.equals("nactive")
                || foo.equals("nactiv") || foo.equals("nacti")
                || foo.equals("nact") || foo.equals("nac")
                || foo.equals("na") || foo.equals("n")) {

Upvotes: 1

Views: 172

Answers (5)

Mike Nakis
Mike Nakis

Reputation: 62005

Originally I thought that what you want is if( foo.indexOf( "inactive" ) != -1 ). But I am wrong. And all answers are wrong. Because what you want is impossible. (Sorry, it was very late night when I was writing my original answer.)

In set theory, every set also contains the empty set. From this it follows that every string contains a portion of the word "inactive", because:

  • the empty string is also a portion of the word "inactive", and
  • every string contains the empty string.

So, @assylias has captured the essence of the problem in his comment to the OP.

One of two things is true: either

  • you have not thought very well what you want to accomplish, or
  • you have not explained very well what it is that you want to accomplish.

As it stands, your question cannot receive any answer other than if( true ).

Upvotes: 2

Harbeer Kadian
Harbeer Kadian

Reputation: 394

If it means it should match if any character used in "inactive" string is part of foo.

You can use regular expression [inactve], it will match foo if foo contains any of the characters mentioned in the regular expression. i is omitted from inactive in regular expression as it is coming twice.

See this link for more details.

Upvotes: 1

niyasc
niyasc

Reputation: 4490

You can use contains(CharSequence) and startsWith(String) methods defined in String class.

See more information in official documentation.

Upvotes: 1

additionster
additionster

Reputation: 628

Try using this

if ("inactive".indexOf(foo) != -1)
{
    System.out.println("Contains!");
}

Upvotes: 5

Ahmed
Ahmed

Reputation: 184

foo.contains("nact");

This is the simplest solution

Upvotes: 1

Related Questions