Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if substring exists in a string

I have a lot of strings, and I need to check if each of them contains a color.

For example :

  • A bird in the sky
  • 22 street of France
  • The dog is blue
  • The cat is black and white

So, the two last strings must return true.

What is the best way to find it?

Regex, or check with any substr() ?

like image 489
bahamut100 Avatar asked Aug 04 '11 07:08

bahamut100


People also ask

How do you check if a substring is in a string in Python?

The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")

How do you find if a substring is present in a string in C++?

Check if a string contains a sub-string in C++This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches. If the item is found, this function returns the position. But if it is not found, it will return string::npos.

How do I find a particular substring in a string in Java?

To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.

How do you check if a string is a substring of another in C?

Search for string inside another string - strstrThe function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.


1 Answers

I always work with strpos since it seems to be the fastest alternative (don't know about regex though).

if(strpos($haystack, $needle) !== FALSE) return $haystack;
like image 144
Quasdunk Avatar answered Oct 20 '22 19:10

Quasdunk