How to Get Unicode Value into a String Objective C - objective-c

I am looking to get the actually unicode value of a character, and put it into an escaped string. I set the title of an NSButton to ± , now I am trying to get the title of this button and convert it back to this "\U00B1";
For Example
unichar theChar = [theButton.title characterAtIndex:0];
//now how would I change the above unichar to an string like #"\\u03b2"

One solution would be:
unichar theChar = ...
NSString *escapeCode = [NSString stringWithFormat:#"\\\\u%04x", theChar];
Note how you need four backslashes to get two in the resulting string.

Related

Objective-C NSString for loop with characterAtIndex

I'm trying to loop through a NSString, character by character, but I'm getting a EXC_BAD_ACCESS error. Do you have an idea how to do this right? I've been googling for hours now but can't figure it out.
Here is my code (.m):
self.textLength = [self.text length];
for (int position=0; position < self.textLength; position++) {
NSLog(#"%#", [self.text characterAtIndex:position]);
if ([[self.text characterAtIndex:position] isEqualToString:#"."]){
NSLog(#"it's a .");
}
}
Thanks a lot!
Characters are not object. characterAtIndex returns unichar, which is actually an integer type unsigned short. You need to use %C instead of %# in NSLog. Also character is not a NSString, so you can't send it isEqualToString. You need to use ch == '.' to compare ch against '.'.
unichar ch = [self.text characterAtIndex:position];
NSLog(#"%C", ch);
if (ch == '.') {} // single quotes around dot, not double quotes
Note that, 'a' is character, "a" is C string and #"a" is NSString. They all are different types.
When you are using %# with unichar ch in NSLog, it is trying to print an object from memory location ch which is invalid. Thus you are getting a EXC_BAD_ACCESS.
characterAtIndex: returns a unichar, so you should use NSLog(#"%C", ...) instead of #"%#".
You also cannot use isEqualToString for a unichar, just use == '.' is fine.
If you want to find the position of all '.'s, you can use rangeOfString. Refer to:
String Programming Guide: Searching, Comparing, and Sorting Strings
Position of a character in a NSString or NSMutableString
characterAtIndex: returns a unichar, which is declared as typedef unsigned short unichar; The format specifier you are using in your calls to NSLog are incorrect, you could just do NSLog(#"%u",[self.text characterAtIndex:position]); or NSLog(#"%C",[self.text characterAtIndex:position]); if you want the actual character to print out.
Also, as a result of unichar being defined the way that it is, it's not a string, so you cannot compare it to other strings. Try something like:
unichar textCharacter = '.';
if ([self.text characterAtPosition:position] == testCharacter) {
// do stuff
}
If you want to find the location of a character in a string you can use this:
NSUInteger position = [text rangeOfString:#"."].location;
if the character or text is not found you will get a NSNotFound:
if(position==NSNotFound)
NSLog(#"text not found!");

searching and replacing an extended ASCII in a string

a noob question here.
I am trying to make an automatic search and replace process for characters' ASCII values in a string.
so, I have a string constructed from a content of a UITextField
NSString *searchText;
searchText = (mmText.text);
then I do a little loop and check all entered characters for their ASCII values. if they're not in the allowed range I want to search and replace them with something else (? for now)
so let's say I am in the loop and I get to a ASCII 45 character (it's a minus sign):
int asciiCode = 45;
now I would like to find the ASCII 45 character in the string and replace it with a question mark
This is what I am doing at the moment:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
NSRange matchSpace;
matchSpace = [searchText rangeOfString: ascStr];
if (matchSpace.location == NSNotFound)
{}
else
NSMutableString *searchandReplace = [NSMutableString stringWithString: searchText];
[searchandReplace replaceCharactersInRange: [searchandReplace rangeOfString: ascStr] withString: #"?"];
mmText.text = searchandReplace;
}
This works fine for a regular ASCII value (0-255), but it doesn't seem to work for the extended ASCII values coming from foreign languages. For example when using the Korean language mode, one of the main character looks like a double crossed W, but when printed via NSLog it looks like a copyright sign. This is probably the reason the search and replace procedure doesn't work for it. It has an ASCII value of 8361.
any ideas ? thank you!
it turns out it was as simple as changing:
NSString *ascStr = [NSString stringWithFormat:#"%c", asciiCode];
to
NSString *ascStr = [NSString stringWithFormat:#"%C", asciiCode];
%c
8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit
%C
16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \ddd or the Unicode hexadecimal format \udddd, where d is a digit

Casting or converting a char to an NSString in Objective-C

How do I convert a char to an NSString in Objective-C?
Not a null-terminated C string, just a simple char c = 'a'.
You can use stringWithFormat:, passing in a format of %c to represent a character, like this:
char c = 'a';
NSString *s = [NSString stringWithFormat:#"%c", c];
You can make a C-string out of one character like this:
char cs[2] = {c, 0}; //c is the character to convert
NSString *s = [[NSString alloc] initWithCString:cs encoding: SomeEncoding];
Alternatively, if the character is known to be an ASCII character (i. e. Latin letter, number, or a punctuation sign), here's another way:
unichar uc = (unichar)c; //Just extend to 16 bits
NSString *s = [NSString stringWithCharacters:&uc length:1];
The latter snippet with surely fail (not crash, but produce a wrong string) with national characters. For those, simple extension to 16 bits is not a correct conversion to Unicode. That's why the encoding parameter is needed.
Also note that the two snippets above produce a string with diferent deallocation requirements. The latter makes an autoreleased string, the former makes a string that needs a [release] call.

is it possible to convert NSString into unichar

I have a NSString object and want to change it into unichar.
int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298
NSString *hex = [NSString stringWithFormat:#"0x%x", decimal]; // hex = 0x300a
NSString *chineseChar = [NSString stringWithFormat:#"%C", hex];
// This statement log a different Chinese char every time I run this code
NSLog(#"%#",chineseChar);
When I see the log, It gives different character every time when I run my code.
m I missing something...?
The %C format specifier takes a 16-bit Unicode character (unichar) as input, not an NSString. You're passing in an NSString, which is getting reinterpreted as an integer character; since the string can be stored at a different address in memory each time you run, you get that address as an integer, which is why you get a different Chinese character every time you run your code.
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET
How about -[NSString characterAtIndex:]? It wants a character index and returns a unichar.

How to get a single NSString character from an NSString

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?
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)];
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".
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.
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);