Cocoa: change each character of a string to a different unicode value?

retrotron

thinking is design
I need to step through a string (character by character) and change each character to a different unicode value. How can I do that?

For example, suppose I have a string "abc" (unicode: x61 x62 x63). I want to step through each character in that string and change the unicode value to a different value: x44 x45 x46 ("DEF"). How do I do that?
 
There's a lot of different ways to do that. One way would be to get the C string version of the NSString (if your string is an NSString) and use a while loop to go through each element in the array. Or you could probably create a new NSMutableString and use characterAtIndex: for the original string and gradually build a new string from the old one. Or, if you use an NSMutableString to store the original string, you could use the replaceCharacters... method.
 
Or you could probably create a new NSMutableString and use characterAtIndex: for the original string and gradually build a new string from the old one.

That sounds like a good approach. So once I get the characterAtIndex:, how do I put append a new unicode character to the new NSMutableString? I can't seem to figure out how to add a specific unicode character.
 
I'd probably just do something like this, but I haven't worked too much with unicode characters and I haven't actually tested this out.

unichar string[max_size];

[theString getCharacters:string];
/* that puts all the values into an array that you can go through */


/* store string back into NSString */
[string release];
[string = [[NSString stringWithCharacters:string length:strlen(string)] retain];
 
I don't know if this works with unicode and cocoa, but in C++ you can simply add to a character. Is there something similar in cocoa? for instance, in C++ you can do something like

CharVariable=CharVariable+3;

which, if CharVariable was, say, A, would make CharVariable become D.

could you use the characterAtIndex: command in coca to do something similar? Like I said, I don't know, just a brainstorm. Hope this helps, sorry if it doesn't! :)
 
Thanks all, this is all very helpful. What if I wanted to append the unicode character 0x03B2 to an NSMutableString. How would I do that?
 
I'm pretty sure (without looking at the documentation) you have to store the character into an NSString first, then append the NSString to the NSMutableString.
 
Okay, I've got it working. Here's what I was looking for:
Code:
[someMutableString appendFormat:@"%C", 0x03B2];
Where 0x03B2 is the desired unicode character code.

Thanks!
 
Back
Top