PDA

View Full Version : how many times a string is repeated in another string


VincenzoDrift
30/12/2015, 04:09 PM
Hi, i have a problem. I need to know how many times a string is repeated in another string.

Example:
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 :D

Jefff
30/12/2015, 04:14 PM
while + strfind "No"

VincenzoDrift
31/12/2015, 09:46 AM
Thanks i try to do this, but don't work.
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?

BroZeus
31/12/2015, 10:18 AM
Use this :

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

VincenzoDrift
31/12/2015, 10:42 AM
Thanks it works, but it give me a warning "tag mismatch" on this line.
if(!strcmp(needle, temp, ignorecase))c++;
How fix?

BroZeus
31/12/2015, 10:49 AM
Ah change the function prototype(function header) to this:
stock GetQuantityStringInString(haystack[], needle[], bool:ignorecase = true)
Add that bold part

Kaliber
31/12/2015, 12:23 PM
The fastest way to do this, is:

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

Speed Results against your function:

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

Greekz :cool: