How to get a single NSString character from an NSString

Objective CCocoa TouchNsstring

Objective C Problem Overview


I want to get a character from somewhere inside an NSString. I want the result to be an NSString.

This is the code I use to get a single character at index it:

[[s substringToIndex:i] substringToIndex:1]

Is there a better way to do it?

Objective C Solutions


Solution 1 - Objective C

This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.

NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];

Solution 2 - Objective C

If you just want to get one character from an a NSString, you can try this.

- (unichar)characterAtIndex:(NSUInteger)index;

Used like so:

NSString *originalString = @"hello";
int index = 2;
NSString *theCharacter = [NSString stringWithFormat:@"%c", [originalString characterAtIndex:index-1]];
//returns "e".

Solution 3 - Objective C

Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use

- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;

if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.

Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.

Solution 4 - Objective C

NSMutableString *myString=[NSMutableString stringWithFormat:@"Malayalam"];
NSMutableString *revString=@"";

for (int i=0; i<myString.length; i++) {
    revString=[NSMutableString stringWithFormat:@"%c%@",[myString characterAtIndex:i],revString];
}
NSLog(@"%@",revString);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnode ninjaView Question on Stackoverflow
Solution 1 - Objective CKris MarkelView Answer on Stackoverflow
Solution 2 - Objective CjoshualmfView Answer on Stackoverflow
Solution 3 - Objective CNo one in particularView Answer on Stackoverflow
Solution 4 - Objective CNeeraj JerauldView Answer on Stackoverflow