If text exists in label, in Xcode

2019-08-31 08:34发布

问题:

Ok so I wanna see if the user has in putted a single word among other words like for example I want the user to say hi, but not only the word hi! For example like this :

Everybody this is XCoder, say hi class. I want an if command that will scan for the word hi and delete it if it is there and if it is not do nothing to the text.

Summary : Scan for particular text, if exists substring it. or remove, I would most likely expecting or expecting a (if) statement more than anything else cause this is a static label, (changing).

回答1:

Referred from other post.. The key is noticing that rangeOfString: returns an NSRange struct, and the documentation says that it returns the struct {NSNotFound, 0} if the "haystack" does not contain the "needle".

 NSString *myString = @"Hi I am asking for help.";
    if ([string rangeOfString:@"Hi"].location == NSNotFound) {
      NSLog(@"%@",myString);
    } else {
      NSString *updated = [myString stringByReplacingOccurrencesOfString:@" am" withString:@""];
      NSLog(@"%@",updated);
    }