count(...)
public
Each other_str parameter defines a set of characters to count. The intersection of these sets
defines the characters to count in
str. Any other_str that starts with a caret (^) is
negated. The sequence c1–c2 means all characters between c1 and c2.
a = "hello world"
a.count "lo"
a.count "lo", "o"
a.count "hello", "^l"
a.count "ej-m"
Show source
/*
* call-seq:
* str.count([other_str]+) => fixnum
*
* Each <i>other_str</i> parameter defines a set of characters to count. The
* intersection of these sets defines the characters to count in
* <i>str</i>. Any <i>other_str</i> that starts with a caret (^) is
* negated. The sequence c1--c2 means all characters between c1 and c2.
*
* a = "hello world"
* a.count "lo"
* a.count "lo", "o"
* a.count "hello", "^l"
* a.count "ej-m"
*/
static VALUE
rb_str_count(argc, argv, str)
int argc;
VALUE *argv;
VALUE str;
{
char table[256];
char *s, *send;
int init = 1;
int i;
if (argc < 1) {
rb_raise(rb_eArgError, "wrong number of arguments");
}
for (i=0; i<argc; i++) {
VALUE s = argv[i];
StringValue(s);
tr_setup_table(s, table, init);
init = 0;
}
s = RSTRING(str)->ptr;
if (!s || RSTRING(str)->len == 0) return INT2FIX(0);
send = s + RSTRING(str)->len;
i = 0;
while (s < send) {
if (table[*s++ & 0xff]) {
i++;
}
}
return INT2NUM(i);
}