SA-MP Forums Archive
Count characters in 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)
+---- Forum: Help Archive (https://sampforum.blast.hk/forumdisplay.php?fid=89)
+---- Thread: Count characters in string (/showthread.php?tid=271309)



Count characters in string - MP2 - 23.07.2011

How do I make a function that can return the number of a certain character in a string? For example I want 'CountChars("~", string) to tell me how many ~'s are in string.

Thanks.


Re: Count characters in string - CaHbKo - 23.07.2011

pawn Код:
CountChars('~', string);

stock CountChars(ch, str[], len = sizeof(str))
{
     new count;
     for(new i; i != len; i++) if(str[i] == ch) count++;
     return count;
}
Untested.


Re: Count characters in string - MP2 - 23.07.2011

Would it be better with strfind though?


Re: Count characters in string - Jefff - 23.07.2011

pawn Код:
stock CountChars(txt[],ch='~')
{
    new d,cnt;
    while(txt[d] != EOS)
    {
        if(txt[d] == ch) cnt++;
        d++;
    }
    return cnt;
}



Re: Count characters in string - CaHbKo - 23.07.2011

Quote:
Originally Posted by MP2
Посмотреть сообщение
Would it be better with strfind though?
Strfind finds a _string_ and returns it's _position_. The function I gave you counts all the _characters_ and returns the _amount_. 2 differences.


Re: Count characters in string - MP2 - 23.07.2011

Works great, thanks a lot <3