split NSString given a number of characters in objective C [closed]

↘锁芯ラ 提交于 2019-12-14 03:29:40

问题


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.



来源:https://stackoverflow.com/questions/16263720/split-nsstring-given-a-number-of-characters-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!