-->

split NSString given a number of characters in obj

2019-09-25 08:01发布

问题:

I have two strings that are taken as input from a textfield in my application. I know that they are both 4 characters in length.

Is there some way I can "halve" those strings, and create two strings per original string that have two characters each?

回答1:

Sure. NSString has the very useful methods "substringToIndex:" and "substringFromIndex:". The magic number (index) here appears to be 2.



回答2:

A simple approach would be to use the NSString substringWithRange: method to obtain each of the pairs of characters you require.

For example:

NSString *sourceString = @"ABCD";

assert([sourceString length] == 4);    // Handle error conditions here.

NSString *firstSection = [sourceString substringWithRange:NSMakeRange(0,2)];
NSString *secondSection = [sourceString substringWithRange:NSMakeRange(2,2)];

See the NSString class reference for more information.