objective c - How to find the number of gaps between words in an NSString? -
given nsstring containing sentence determine number of gaps between words.
i use [[thestring componentsseparatedbystring:@" "].
but work if each gap single space character, there multiple.
you can use nsregularexpression, like:
nsstring *test = @"the quick brown fox jumped on lazy dog"; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@"\\s+" options:0 error:null]; nsuinteger num = [regex numberofmatchesinstring:test options:0 range:nsmakerange(0, test.length)]; nslog(@"num: %lu", num);
the regular expression "\s+" matches 1 or more whitespace characters (it's written here "\" because need literal backslash in nsstring). numberofmatchesinstring:options:range:
counts each run of 1 or more whitespace characters match, want.
Comments
Post a Comment