如何将 NSString 的每个字符添加到 NSArray 中?
我正在寻找一种传递 NSString 的方法,它包含 4 个字符,整体代表一个 4 位数字,如 0741,我一直在四处寻找并不断遇到这个函数
myArray = [dataString componentsSeparatedByString:@"\r\n"];
ComponentsSeparatedByString...如果我的组件不是,我该怎么办分开了?
好吧,在查看下面发布的链接后,我发现了 NSRange,并设法让它与下面的解决方案完美配合,但是感觉有点冗长,而且可能比需要的更笨重......让我知道你是什么思考以及我可以做出哪些改进。
NSRange MyOneRange = {0, 1};
NSRange MyTwoRange = {1, 1};
NSRange MyThreeRange = {2, 1};
NSRange MyFourRange = {3, 1};
NSString *firstCharacter = [[NSString alloc] init];
NSString *secondCharacter = [[NSString alloc] init];
NSString *thridCharacter = [[NSString alloc] init];
NSString *fourthCharacter = [[NSString alloc] init];
firstCharacter = [myFormattedString substringWithRange:MyOneRange];
secondCharacter = [myFormattedString substringWithRange:MyTwoRange];
thridCharacter = [myFormattedString substringWithRange:MyThreeRange];
fourthCharacter = [myFormattedString substringWithRange:MyFourRange];
NSLog(@"%@, %@, %@, %@", firstCharacter, secondCharacter, thridCharacter, fourthCharacter);
I am looking for a way to pass a NSString, which contains 4 charcters that in whole represent a 4 digit number like 0741, I have been looking around and keep coming across this function
myArray = [dataString componentsSeparatedByString:@"\r\n"];
componentsSeparatedByString... what can I do if my components are not separated?
Well, after checking out the link posted below I found NSRange, and have managed to get it working perfectly with this solution below, however it feels abit drawn out and maybe abit more bulky than it needs to be... let me know what you think and what improvements I could make.
NSRange MyOneRange = {0, 1};
NSRange MyTwoRange = {1, 1};
NSRange MyThreeRange = {2, 1};
NSRange MyFourRange = {3, 1};
NSString *firstCharacter = [[NSString alloc] init];
NSString *secondCharacter = [[NSString alloc] init];
NSString *thridCharacter = [[NSString alloc] init];
NSString *fourthCharacter = [[NSString alloc] init];
firstCharacter = [myFormattedString substringWithRange:MyOneRange];
secondCharacter = [myFormattedString substringWithRange:MyTwoRange];
thridCharacter = [myFormattedString substringWithRange:MyThreeRange];
fourthCharacter = [myFormattedString substringWithRange:MyFourRange];
NSLog(@"%@, %@, %@, %@", firstCharacter, secondCharacter, thridCharacter, fourthCharacter);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了即兴发挥你的方法,
To improvise on your approach,
你有很多选择......有
- (unichar)characterAtIndex
方法启动。我建议阅读 NSString 文档(有一个名为“获取字符和字节”的方法部分)。You have many options... there's the
- (unichar)characterAtIndex
method, to start. I suggest reading the NSString documentation (there's a section of methods called "Getting Characters and Bytes").像这样的东西应该可以很好地工作:
Something like this should work nicely: