Count characters in string
#1

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.
Reply
#2

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.
Reply
#3

Would it be better with strfind though?
Reply
#4

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

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.
Reply
#6

Works great, thanks a lot <3
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)