count(*args)
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
static VALUE
rb_str_count(int argc, VALUE *argv, VALUE str)
{
char table[256];
rb_encoding *enc = 0;
VALUE del = 0, nodel = 0;
char *s, *send;
int i;
int ascompat;
if (argc < 1) {
rb_raise(rb_eArgError, "wrong number of arguments");
}
for (i=0; i<argc; i++) {
VALUE s = argv[i];
StringValue(s);
enc = rb_enc_check(str, s);
tr_setup_table(s, table, i==0, &del, &nodel, enc);
}
s = RSTRING_PTR(str);
if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0);
send = RSTRING_END(str);
i = 0;
ascompat = rb_enc_asciicompat(enc);
while (s < send) {
unsigned int c;
int clen;
if (ascompat && (c = *(unsigned char*)s) < 0x80) {
clen = 1;
if (table[c]) {
i++;
}
s++;
}
else {
c = rb_enc_codepoint(s, send, enc);
clen = rb_enc_codelen(c, enc);
if (tr_find(c, table, del, nodel)) {
i++;
}
s += clen;
}
}
return INT2NUM(i);
}