我正在寻找一种传递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);
答案 0 :(得分:10)
即兴发挥你的方法,
NSRange theRange = {0, 1};
NSMutableArray * array = [NSMutableArray array];
for ( NSInteger i = 0; i < [myFormattedString length]; i++) {
theRange.location = i;
[array addObject:[myFormattedString substringWithRange:theRange]];
}
答案 1 :(得分:2)
你有很多选择......开始使用- (unichar)characterAtIndex
方法。我建议阅读NSString文档(有一节称为“获取字符和字节”的方法)。
答案 2 :(得分:1)
这样的事情应该很好用:
NSString *dataString = @"0741";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[dataString length]];
for (int i = 0; i < [dataString length]; i++) {
NSString *singleCharacter = [NSString stringWithFormat:@"%c", [dataString characterAtIndex:i]];
[characters addObject:singleCharacter];
}