开发者

separate a word into characters using string methods

开发者 https://www.devze.com 2022-12-16 23:17 出处:网络
Trying to split what the user writes in the text field, into an array full of the characters in the things he typed.

Trying to split what the user writes in the text field, into an array full of the characters in the things he typed.

here is what I have so far

-(IBAction) generateFlashNow:(id)sender{

[textField resignFirstResponder];
NSString *string1 = textField.text;
NSString *string2 = [string1 stringByRe开发者_开发百科placingOccurrencesOfString:@"" withString:@","];
NSArray *arrayOfLetters = [string2 componentsSeparatedByString:@","];

NSLog(@"Log Array :%@", arrayOfLetters);

//NSArray *imageArray = [[NSArray alloc] init];

NSLog(@"Log First Letter of array: %@",[arrayOfLetters objectAtIndex:0]);

}

What am I doing wrong?


stringByReplacingOccurrencesOfString is not doing anything when you pass an empty string "" so string2 is an identical copy of string1, hence no commas and the split operation fails.

There are many ways to get this done. I can think of two:

Convert to a character array:

NSString *string = @"Hello";
const char *characters = [string UTF8String];
for(int i=0; i<sizeof(characters); i++) {
    NSLog(@"%c", characters[i]);
}

Or, if you only want to deal with objects, loop through each method and hand-create the array:

NSString *string = @"Hello";
NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i = 0; i < [string length]; i++) {
    NSString *myChar = [NSString stringWithFormat:@"%c", [string characterAtIndex:i]];
    [array addObject:myChar];
}

You could add the above logic to a method like toArray as a category in NSString itself, so all strings get this functionality if that's a common case for your application. Checkout this article for more information about categories. You'd simply call [someString toArray] to get it's array representation.

0

精彩评论

暂无评论...
验证码 换一张
取 消