Getting the last word of an NSString

前端 未结 7 1078
滥情空心
滥情空心 2020-12-17 00:38

As the title suggests, I would like to get the last word out of an NSString. I thought using this code:

NSArray *listItems = [someNSStringHere componentsSepa         


        
7条回答
  •  离开以前
    2020-12-17 00:41

    You could use NSString's function rangeOfSubstring:options: to determine it. For example:

    Search the string for a space, using a backwards search option to start the search from the end of the string.

    NSRange r = [string rangeOfString:@" " options:NSBackwardsSearch];

    This will find the location of the last word of the string. Now just get the string using substringWithRange: For Example:

    NSRange found = NSMakeRange(NSMaxRange(r), string.length - NSMaxRange(r)); NSString *foundString = [string substringWithRange:found];

    Where r is the range from earlier.

    Also be careful to make sure that you check r actually exists. If there is only 1 word in the string, then r will be {NSNotFound, 0}

    Hope I could help!

    Ben

提交回复
热议问题