Better Way to Detect If a String Contains Multiple Words

Better way to detect if a string contains multiple words

Editors note: Despite being heavily upvoted and accepted, this does not function the same as the code in the question. execute is called on the first match, like a logical OR.

You could use an array:

String[] matches = new String[] {"adsf", "qwer"};

bool found = false;
for (String s : matches)
{
if (input.contains(s))
{
execute();
break;
}
}

This is efficient as the one posted by you but more maintainable. Looking for a more efficient solution sounds like a micro optimization that should be ignored until proven to be effectively a bottleneck of your code, in any case with a huge string set the solution could be a trie.

How to check if a string contains multiple words on different locations

If you want to know the length of the match, e.g. using regex:

var str = "There idea";

var pattern = new RegExp("\\b" + str.replace(/ +/g, "\\b.*\\b") + "\\b", "i")
console.log(pattern)

var strings = [
"There is this one thing that I'm trying to do but I have no idea how",
"I really have no clue how too fix it",
"Hopefully maybe someone can help me"
]

for( i=0; i < strings.length; i++ )
if( res=strings[i].match(pattern) )
console.log( res[0], res[0].length )

Check if a string contain multiple specific words

For this, you will need Regular Expressions and the preg_match function.

Something like:

if(preg_match('(bad|naughty)', $data) === 1) { } 

The reason your attempt didn't work

Regular Expressions are parsed by the PHP regex engine. The problem with your syntax is that you used the || operator. This is not a regex operator, so it is counted as part of the string.

As correctly stated above, if it's counted as part of the string you're looking to match: 'bad || naughty' as a string, rather than an expression!

Fastest/most minimal way to check if string contains multiple words

I would iterate through the string, counting the words and iterating over any consecutive whitespace.

  • Increase word count whenever moving from whitespace to non-whitespace.
  • Increase word count if string starts with non-whitespace

    int countWords(string& toCount, const string& whitespace){
    enum countStatus {
    startOfString,
    initialWhitespace,
    movePastWord,
    movePastWhitespace
    } status=startOfString;

    int wordCount=0;

    for(char& c : toCount) {
    bool characterIsWhitespace=false;

    if (whitespace.find(c)!=string::npos) {
    characterIsWhitespace=true;
    }

    switch(status) {
    case startOfString:
    if (characterIsWhitespace) {
    status=initialWhitespace;
    } else {
    status=movePastWord;
    wordCount++;
    }
    break;

    case initialWhitespace:
    if (!characterIsWhitespace) {
    wordCount++;
    status=movePastWord;
    }
    break;

    case movePastWord:
    if (characterIsWhitespace) {
    status=movePastWhitespace;
    }
    break;

    case movePastWhitespace:
    if (!characterIsWhitespace) {
    wordCount++;
    status=movePastWord;
    }
    }
    }

    return wordCount;
    }

Python - Check if a string contains multiple words

Basic implementation

Generally, you use split() to split a string of words into a list of them. If the list has more than one element, it's True (i.e. you could print yes)

def contains_multiple_words(s):
return len(s.split()) > 1

Punctuation support

To support punctuation etc as well, you can split on a regular expression, via the re module's split command:

import re

def contains_multiple_words(s):
return len(re.compile('\W').split(s)) > 1

The regular expression character class \W means any single non-word character, e.g. punctuation or spaces (see the Python regex syntax guide for details).

Thus, splitting on this instead of just space (the default in the first example) allows for a more realistic idea of "words".

Check if multiple strings exist in another string

You can use any:

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

Similarly to check if all the strings from the list are found, use all instead of any.

Php check if string contains multiple words

use

substr_count

for an array use the following function

function substr_count_array( $haystack, $needle ) {
$count = 0;
foreach ($needle as $substring) {
$count += substr_count( $haystack, $substring);
}
return $count;
}


Related Topics



Leave a reply



Submit