Author Topic: [RESOURCE] Search for a word in a string  (Read 3219 times)

Code: [Select]
function strStrW(%string, %searchForWord)
{
    for(%i=0;%i<=getWordCount(%string)-1;%i++)
    {
if(getWord(%string,%i) $= %searchForWord)
    return %i;
    }
    return -1;
}

Example 1: strStrW("cakemaker is very happy","ca") would return -1, unlike strStr.

Example 2: strStrW("cakemaker is very happy","very") would return 2.

It's good to have this handy.


make it return false instead of -1

or do those both work

make it return false instead of -1

or do those both work

false == 0

make it return false instead of -1

or do those both work
False would equal 0, and then how do you tell the difference between not found, and found at the beginning of the string?

Code: [Select]
function strStrW(%string, %searchForWord)
{
    for(%i=0;%i<=getWordCount(%string)-1;%i++)
    {
if(getWord(%string,%i) $= %searchForWord)
    return %i;
    }
    return -1;
}

Example 1: strStrW("cakemaker is very happy","ca") would return -1, unlike strStr.

Example 2: strStrW("cakemaker is very happy","very") would return 2.

How about this instead:
Code: [Select]
function strStrW(%string, %searchForWord)
{
  return strStr(" " @ %string @ " ", " " @ %searchForWord @ " " );
}

for big strings, it should run a lot faster

That will not return the WORD index, believe me I literally thought of the exact same code.

What about this
Code: [Select]
function strStrW(%s,%sw)
{
       return strPos(" " @ %s @ " ", " " @ %sw @ " " );
}
?
« Last Edit: September 04, 2012, 06:11:09 PM by Brian Smithers »

not only will it not work because %string doesn't exist, but it was JUST mentioned two posts above yours.

Good god I probably need this.

I knew there was a better way to do this, so here it is:

Code: [Select]
function findWordInString(%string, %word)
{
%word = trim(%word);
%index = striPos(" " @ %string @ " ", " " @ %word @ " ");
if(%index < 2)
return %index;

%before = getSubStr(%string, 0, %index);
return strLen(%before)-strLen(strReplace(%before, " ", ""));
}
This will do the exact same thing, but without any for loops.

I knew there was a better way to do this, so here it is:

Code: [Select]
function findWordInString(%string, %word)
{
%word = trim(%word);
%index = striPos(" " @ %string @ " ", " " @ %word @ " ");
if(%index < 2)
return %index;

%before = getSubStr(%string, 0, %index);
return strLen(%before)-strLen(strReplace(%before, " ", ""));
}
This will do the exact same thing, but without any for loops.
neeat.

This will do the exact same thing, but without any for loops.
For loops aren't the devil's creation, and striPos uses a for loop in C++ so technically it still utilizes a for loop.

For loops aren't the devil's creation, and striPos uses a for loop in C++ so technically it still utilizes a for loop.
when did i say for loops were bad
they're just a bit slower that's all.