SA-MP Forums Archive
how many times a string is repeated in another string - Printable Version

+- SA-MP Forums Archive (https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: how many times a string is repeated in another string (/showthread.php?tid=597392)



how many times a string is repeated in another string - VincenzoDrift - 30.12.2015

Hi, i have a problem. I need to know how many times a string is repeated in another string.

Example:
Code:
new string[128], string2[128];
string = "No/nNo/nNo";
string2= "No";
I need to know how many times the string "No"(string2) is repeated in "No/nNo/nNo"(string1).
The result shoud be 3 times. What function can I use?

P.S. Sorry for my bad english


Re: how many times a string is repeated in another string - Jefff - 30.12.2015

while + strfind "No"


Re: how many times a string is repeated in another string - VincenzoDrift - 31.12.2015

Thanks i try to do this, but don't work.
Code:
stock GetQuantityStringInString(haystack[], needle[])
{
	new pos,
		result,
		count;
	for(;;)  //if i use while(true) it give me a warning
	{
	    result = strfind(haystack, needle, false, pos);
	    pos += result;
	    if(result == -1)
	    {
	        break;
	    }
	    else
		{
            count++;
		}
	}
	return count;
}
Any suggestions?


Re: how many times a string is repeated in another string - BroZeus - 31.12.2015

Use this :
PHP Code:
stock GetQuantityStringInString(haystack[], needle[], ignorecase true)
{
    new 
temp[30], 0;
    for(new 
0strlen(haystack)-strlen(needle); <= l; ++i)
    {
        
strmid(temphaystackii+strlen(needle));
        if(!
strcmp(needletempignorecase))c++;
    }
    return 
c;




Re: how many times a string is repeated in another string - VincenzoDrift - 31.12.2015

Thanks it works, but it give me a warning "tag mismatch" on this line.
Code:
if(!strcmp(needle, temp, ignorecase))c++;
How fix?


Re: how many times a string is repeated in another string - BroZeus - 31.12.2015

Ah change the function prototype(function header) to this:
Quote:

stock GetQuantityStringInString(haystack[], needle[], bool:ignorecase = true)

Add that bold part


Re: how many times a string is repeated in another string - Kaliber - 31.12.2015

The fastest way to do this, is:

PHP Code:
stock static countStrings(const string[], const needle[])
{
    new 
c;
    for(new 
i=strfind(string,needle,true); i!=-1i=strfind(string,needle,true,i+1)) c++;
    return 
c;

Speed Results against your function:

Code:
Your time with 100.000x: 3818ms
My time with 100.000x: 1466ms
Greekz