Friday, 15 May 2015

ios - Remove Duplicated Words From NSString and Save as New NSString -



ios - Remove Duplicated Words From NSString and Save as New NSString -

i have scenarios in may have nsstring contains several words, of them duplicated. want take string looks like:

one 2 3 3 3 2 2 2 1 1 2 3

and create like:

one 2 3

there may times exact length of original nsstring different well. have far is:

nsstring *hereitis = @"first sec 3rd sec 3rd first first first"; nsarray *words = [hereitis componentsseparatedbycharactersinset:[nscharacterset whitespacecharacterset]]; nscountedset *countedset = [nscountedset setwitharray:words]; nsmutablearray *finalarray = [nsmutablearray arraywithcapacity:[words count]]; for(id obj in countedset) { if([countedset countforobject:obj] == 1) { [finalarray addobject:obj]; } } nsstring *string = [finalarray componentsjoinedbystring:@" "]; nslog(@"string%@", string);

this however, returns string in array, , not of words.

this can done way less painlessly. nsset doesn't allow duplicate entries. so, can break string array, , utilize array create set. there, have convert back, , dupes removed.

nsstring *inputstring = @"one 2 3 3 3 2 2 2 1 1 2 three"; nsset *aset = [nsset setwitharray:[inputstring componentsseparatedbystring:@" "]]; nsstring *outputstring = [aset.allobjects componentsjoinedbystring:@" "]; nslog(@"___%@___",outputstring); // outputs "___one 2 three___"

ios objective-c nsstring nsmutablearray nsarray

No comments:

Post a Comment