Pregunta

I have an instance of NSMutableString called MyMutableStr and I want access its character at index 7.

For example:

unsigned char cMy = [(NSString*) MyMutableStr characterAtIndex:7];

I think this is an ugly way; it's too much code.

My question is: Are there more simple ways in Objective-C to access the character in NSMutableString?

Like, in C language we can access a character of a string using [ ] operator:

unsigned char cMy = MyMutableStr[7];
¿Fue útil?

Solución

The way of doing it is to use characterAtIndex:, but you don't need to cast it to a NSString pointer, since NSMutableString is a subclass of NSString. So it isn't that long, but if you still don't find it comfortable, I suggest to use UTF8String to obtain a C string over which you can iterate using the brackets operator:

const char* cString= [MyMutableStr UTF8String];
char first= cString[0];

But remember this (taken from NSString class reference):

The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.

Otros consejos

As others said characterAtIndex: but a few things you might want to consider carefully.

First you're dealing with an mutable string. You want to be careful to avoid it changing out from under you. One way is to an immutable copy and use that for the op.

Second, you're dealing with Unicode so you may want to consider normalizing your string to get a precomposed form as some visual representations may be more than one actual unichar. That's often a stumbling block for folks.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top