Tuesday 15 September 2015

ios - Tokenize an NSString for filtering data (search) -



ios - Tokenize an NSString for filtering data (search) -

i'm trying implement search filtering info source used populate uitableview.

basically, i'm trying allow people set in multiple words , split 1 string tokens , iterate through each object in datasource see if can find of search tokens anywhere in object's properties or sub-properties.

if user types in multiple words separated spaces, trivial case of using -componentsseparatedbystring:.

i'm trying, however, solve case user might set in comma-separated list of items.

so, easy entry tokenize this:

"word1 word2 word3"

i want able tokenize this:

"word1, word2, word3"

the problem see that, because don't assume user come in commas, can't replace/remove white space.

i see kludgy ways implement want, consists of splitting first on white space, iterating array, splitting on commas, iterating overall array, removing "empty" tokens. think work, hoping more elegant way this, since might decide add together 3rd delimiter @ point, create solution exponentially more complex.

so far, i'm intrigued using nscharacterset in combination -componentsseparatedbycharactersinset. i'm having problem method, though.

here's i'm trying far:

nsmutablecharacterset *delimiters = [nsmutablecharacterset charactersetwithcharactersinstring:@","]; [delimiters addcharactersinstring:@" "]; nsarray *tokens = [searchtext componentsseparatedbycharactersinset:delimiters];

the problem i'm encountering this:

suppose searchtext (above) "word,". in case, tokens array becomes this:

[@"word", @""]

so, trying out, appear (at first glance) still have iterate tokens array remove empty items. again, possible, have feeling there's improve way.

is there improve way? misusing nscharacterset?

use enumeratesubstringsinrange:options:usingblock:, , pass nsstringenumerationbywords option. separate string individual words, , strip out spaces, commas, semicolons, etc. instance, code,

- (void)viewdidload { [super viewdidload]; nsmutablearray *words = [nsmutablearray new]; nsstring *text = @"these , some, words commas; semi colons: colons , period."; [text enumeratesubstringsinrange:nsmakerange(0, text.length) options:nsstringenumerationbywords usingblock:^(nsstring *substring, nsrange substringrange, nsrange enclosingrange, bool *stop) { [words addobject:substring]; }]; nslog(@"%@", words); }

gives output,

2014-10-22 11:13:25.728 gettingwordsfromstringproblem[859:270592] ( these, are, some, words, with, commas, semicolons, colons, and, period )

ios objective-c nsstring tokenize

No comments:

Post a Comment