Friday, 15 May 2015

objective c - How to loop through txt file and then replace bad words in iOS -



objective c - How to loop through txt file and then replace bad words in iOS -

this question has reply here:

replacing bad words in string in objective-c 1 reply

hello i'm new ios , im trying loop through txt file have imported textview , replace "bad words" "better words" have 3 arrays 1 holding txt file converted array. list of bad words should , list of words in should replaced with. programme should able scan text , bad words , according value of bad word replace improve word. have far when scanning text. i'm trying test see if bad words recognized , right doesn't work.

- (ibaction)scantext:(id)sender { nsstring *contents = [nsstring stringwithcontentsoffile:textfile encoding:nsutf8stringencoding error:nil]; nsarray *lines = [contents componentsseparatedbystring:@" "]; nsarray *badword = [nsarray arraywithobjects: @"objectivity",@"people",nil]; nsarray *goodword = [nsarray arraywithobjects:@"default", @"creepers"]; (nsstring* bad in badword) if ([lines containsobject: bad]) { self.textview.text = [textfile stringbyreplacingoccurrencesofstring:bad withstring:@"##"]; } }

simply utilize nsregularexpression. mind you, haven't thought bunch how regex should be, should work cases.

edit: missed replacement part. here replacement:

nsstring *string = @"this paragraph bad words don't want!!"; nsarray *badwords = @[@"bad", @"words"]; nsarray *betterwords = @[@"good", @"something"]; nsmutablestring *pattern = [nsmutablestring stringwithstring:@"([^a-za-z]?)("]; nsstring *pipe = @""; (nsstring *badword in badwords) { [pattern appendstring:pipe]; [pattern appendstring:badword]; pipe = @"|"; } [pattern appendstring:@")([^a-za-z]?)"]; nsmutablestring *finalstring = [string mutablecopy]; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:pattern options:0 error:nil]; [regex enumeratematchesinstring:string options:0 range:nsmakerange(0, string.length) usingblock:^(nstextcheckingresult *result, nsmatchingflags flags, bool *stop) { nsrange badrange = [result rangeatindex:2]; nsstring *badword = [string substringwithrange:badrange]; nsinteger index = [badwords indexofobject:badword]; nsstring *betterword = betterwords[index]; nsinteger offset = finalstring.length - string.length; badrange.location += offset; [finalstring replacecharactersinrange:badrange withstring:betterword]; }]; nslog(@"%@", finalstring);

result:

2014-06-18 [71719:60b] paragraph don't want!!

anyways, not trying solve regex problem, objective-c problem of how tackle problem.

objective-c regex string parsing nsregularexpression

No comments:

Post a Comment