I'm trying to create an NSMutableArray of characters.
lowerCaseLetters = [NSMutableArray new];
for (char crt = 'a'; crt <= 'z'; crt ++) {
NSString *chrStr = [NSString stringWithCString:&crt encoding:NSUTF8StringEncoding];
[lowerCaseLetters addObject:chrStr];
}
NSLog(@"%@",lowerCaseLetters);
Result:
"a@Ip",
"b@Ip",
"c@Ip",
"d@Ip",
"e@Ip",
"f@Ip",
"g@Ip",
"h@Ip",
"i@Ip",
"j@Ip",
"k@Ip",
"l@Ip",
"m@Ip",
"n@Ip",
"o@Ip",
"p@Ip",
"q@Ip",
"r@Ip",
"s@Ip",
"t@Ip",
"u@Ip",
"v@Ip",
"w@Ip",
"x@Ip",
"y@Ip",
"z@Ip"
)
Why do I get this? Is there a better way to do this? PS: Sometimes this crashes with "insertObject:atIndex:" can not insert nil object.... Why?
This is undefined behavior:
NSString *chrStr = [NSString stringWithCString:&crt encoding:NSUTF8StringEncoding];
The problem is that &crt
is not a C string, because C strings must be null-terminated. You can fix it like this:
char buf[2];
buf[0] = crt;
buf[1] = '\0';
NSString *chrStr = [NSString stringWithCString:buf encoding:NSUTF8StringEncoding];
You could also use stringWithFormat:
for a simpler approach, like this:
NSString *chrStr = [NSString stringWithFormat:@"%c", crt];
Try this...
NSString *stringWithComma = @"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
NSArray *lowerCaseLetters = [[NSArray new] init];
lowerCaseLetters = [stringWithComma componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
NSLog(@"Array %@",lowerCaseLetters);
This gives you an NSArray. If you need a NSMutableArray, you have to copy from the NSArray.
or simply allocate
NSMutableArray *lowerCaseLetters = [[NSMutableArray alloc] initWithObjects: @"a", @"b",...,@"z", nil];
The first approach is dynamic though as you could create stringWithComma dynamically with any values in it.
Following on from dasblinkenlight, another approach is
for (unichar crt = 'a'; crt <= 'z'; crt ++) // note crt is now unichar
{
NSString *chrStr = [NSString stringWithCharacters: &crt length: 1];
[lowerCaseLetters addObject:chrStr];
}
Following on from user2734323 another approach is
lowerCaseLetters = [@[ @"a", @"b", @"c", .... , @"x", @"y", @"z" ] mutableCopy];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.