I'm confused. I'm parsing json string.
Before parsing, I check what is the content of the NSString.
In Xode4:
When I click on the NSString variable "print description"
The console show the value as \u434 \u433 format of the UTF-8
When I call NSLog("%#",content) the console show the "readble" character of the UTF-8 encoding.
Why is this different? How can I know that the string I got to parse is 100% UTF-8 ?
Thanks.
If you can see the Cyrillic characters you're looking for, rather than the escapes, through any method, then you're working with a UTF-8 string.
The "-description" method is not what you want to use here. It's more likely to show escaped characters; in particular, any time you store a value in a property list item like an NSArray or NSDictionary, its -description will generally escape any characters other than plain ASCII.
NSLog is a more reliable guide, because it doesn't use -description. If it's showing up in NSLog, it's probably just fine.
If you want to be absolutely sure your string is properly encoded UTF-8, the best way to test it is to display it. Create a text interface element (an NSTextField or UITextField) in your user interface, wire it up, and set your string as the value. If it displays there, it is properly formatted.
Short version: if it shows up in the debugger as escaped characters, it doesn't necessarily mean it's not UTF8. If it's showing up anywhere (including NSLog) with the proper characters, it's probably in the proper encoding. If you want to be sure, set up a test interface element and see how it looks there.
Related
NSLog displays unknown garble with the following code:
NSString *sampleStr = #"你好";
NSLog(sampleStr);
But it outputs:
As I send the above characters to backend, backend shows
?????
How do I fix this problem?
What the problem specifically? NSLogging or the backend one?
If the former, first of all, you should use string formatting to output strings instead of passing the NSString object directly. This must give you desired output:
NSLog(#"%#", sampleStr);
Though, I tried your code without changes in Xcode 13.1 and it gave me the desired output nevertheless. So, probably the problem is somewhere else, not in your NSLog:
NSString *sampleStr = #"你好";
// "Format string is not a string literal (potentially insecure)"
NSLog(sampleStr); // 你好
NSLog(#"%#", sampleStr); // 你好
If you mean backend as your problem, it depends on how you "send" it to backend (in a body as data, as an HTTP parameter as text, with/without escaping, etc.) and whether your backend code supports the input you provide. To answer that more precisely we should have more information.
I have a list of words like: hello hi bonjour etc.
I'm literally adding #"" around every word manually. It's not bad, but when you have thousands of words it can get really tedious. Is there a method, where you input a bunch plain text like hello hi and it turns it into: #"hello" #"hi", which I can then copy into code, or do I have to do this manually?
the
be
and
of
a
What I've done in similar cases is use an editor's text replacement feature to replace all blanks with (in your case) " #". You may have to get a bit fancier if you don't have blanks at the start and end of each line, or you have multiple adjacent blanks, etc, but the general technique works.
It sounds like what you want is NSString's componentsSeparatedByString: method. You can enter in a bunch of plain text into some text field or text view, get the raw string, and then push that through "componentsSeparatedByString:#" "" (make sure there's one space in there) and out comes an array of words.
You could try loading the strings from a Plist -- inserting them into code is kind of ugly. Something like [NSDictionary dictionaryWithContentsOfURL:urlToMyPlist] or [NSArray arrayWithContentsOfURL:urlToMyPlist]
Look at the docs for NSString and you'll find the -initWithCharacters:length: method, which you can use to create strings. If you have a string that you want to break up into smaller strings, use -componentsSeparatedByString:.
When I insert Hebrew (LTR) string into NSMutableArrey, the string is distorted somehow.
What do I do?
NSString *peace = #"שלום";
NSLog(#"peace - %#", peace);
NSMutableArray *peaceArrey = [[NSMutableArray alloc]initWithCapacity:1];
[peaceArrey addObject:peace];
NSLog(#"peaceArrey - %#",peaceArrey);
And here is the log:
peace - שלום
peaceArrey - (
"\U05e9\U05dc\U05d5\U05dd"
)
everything should be ok, try NSLog(#"%#", peaceArrey[0]);
the result you are seeing is just the way NSArrays are printed: unicode chars are represented as their codes.
Don't mistake the representation that gets logged as the actual value of the object. NSArray's description is in an old-style property list format. Among other things, that means that non-ASCII values in strings are represented as escape sequences. You're seeing the Unicode characters as a series of UTF-16 code units expressed as escape sequences.
When using the %# format specifier NSLog calls description on the argument to log the string.
In case of a plain string this method just returns the string:
NSLog(#"string: %#", #"שלום");
// prints שלום
If you, on the other hand, put the string into an array, the NSArray's description method is called which, in turn, calls descriptionWithLocale:indent:.
This method just creates a property list formatted string. It uses the NSPropertyListOpenStepFormat which is ASCII encoded. That's why it has to escape the hebrew unicode characters.
I need to make chemistry formulas (SO4^2-), and the easiest way to make subscripts and superscripts seems to be adding UTF-8 characters, since KCTSuperscriptAttributeName: property of NSAttributedString doesn't work.
Is it possible for me to make an nsstring with normal characters and utf-8 characters?
Thanks
According to NSString Reference "NSString is implemented to represent an array of Unicode characters, in other words, a text string."
It would be convenient to write as below:
NSString* myStr = #"Any Unicode Character You Want";
Just make sure that your default text encoding is unicode.
Justin's answer is good but I think what you might really be looking for is NSAttributedString (documentation linked for you) or NSMutableAttributedString, where you can add superscripts, subscripts, and other character styles that NSString by itself can't handle.
Take a look at other NSAttributedString questions here or via Google, like this potentially related question or this one.
Hope this helps you out!
yes. i assume you know the normal approach to make an NSString - here's one method to create an NSString from a utf8 string: -[NSString initWithUTF8String:].
I was writing a CLI-Tool for Mac OS X (10.5+) that has to deal with command-line arguments which are very likely to contain non-ASCII characters.
For further processing, I convert these arguments using +[NSString stringWithCString:encoding:].
My problem is, that I couldn't find good information on how to determine the character-encoding used by the shell in which said cli-tool is running in.
What I came up with as a solution is the following:
NSDictionary *environment = [[NSProcessInfo processInfo] environment];
NSString *ianaName = [[environment objectForKey:#"LANG"] pathExtension];
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding( (CFStringRef)ianaName ) );
NSString *someArgument = [NSString stringWithCString:argv[someIndex] encoding:encoding];
I find that a little crude, however -- which makes me think that I missed out something obvious...but what?
Is there a saner/cleaner way of achieving essentially the same?
Thanks in advance
D
The answer depends on what the non-asciiness comes from.
In OS X, the environment variable LANG does not reflect the choice of language in the GUI. Very few people will set LANG at the command line.
The choice of the "system encoding" at the GUI is stored in ~/.CFUserTextEncoding, and can be obtained by CFStringGetSystemEncoding, see this Apple doc.
That said, this "system encoding" is rarely used except in a very old, non-unicode aware softwares. Any sane Cocoa program uses just Unicode and nothing else.
In particular, the file path at the level of Cocoa is always encoded in (a variant of) UTF-8. So, to get an NSString from a C string, use
NSString*string=[NSString stirngWithCString:cString encoding:NSUTF8Encoding];
and to get a C-string for the file path from an NSString, use
char*path=[string fileSystemRepresentation];
Here it is recommended not to use just [string UTF8String], due to the subtlety, see this Apple doc.
So, I recommend you not to care about the encoding and just assume UTF-8.
That said, there might be a very small number of people who sets LANG on the command line, and you might want to take care of them. Then, what you did is the only thing I can come up with.
Can’t you just use [[NSProcessInfo processInfo] arguments]?
Okay, it turns out there seems to be none!
As Yuji pointed out, the underlying encoding of filenames is UTF-8, no matter what. Therefore, one needed to handle two scenarios:
Arguments that are typed in, character for character, by the user.
Arguments that are tab-completed or the output of commands like ls, as they do not convert any characters.
The second case is simply covered by the assumption of UTF-8.
The first case, however, is problematic:
On Mac OS 10.6, $LANG contains the IANA-name of the used encoding like de_DE.IANA_NAME.
Prior to Snow Leopard, this is not the case for charsets other than UTF-8!
I didn't test each and every charset I could think of, but none of the european ones were included. Instead, $LANG only was the language-locale (de_DE in my case)!
Since the results of calling +[NSString stringWithCString:encoding:] with an incorrect encoding are undefined, you cannot safely assume that it will return nil in that case* (if eg. it's ASCII-only, it might work perfectly fine!).
What adds to the overall mess is that $LANG is not guarateed to be around, anyway: There's a checkbox in Terminal.app's preferences, that enables a user to not set $LANG at all (not to speak of X11.app which doesn't seem to handle any non-ASCII input...).
So what's left:
Check for presence of $LANG. If it's not set, Goto:4!
Check if $LANG contains information on the encoding. If it doesn't, Goto:4!
Check if the encoding you find there is UTF-8. If it is Goto:6, else...
If argc is greater than 2 and [[NSString stringWithCString: argv[0] encoding: NSUTF8StringEncoding] isEqualToString: yourForceUTFArgumentFlag], print that you are forcing UTF-8 now and Goto 6. If not:
Assume you don't know anything, issue a warning that your user should set the Terminal encoding to UTF-8 and may consider passing yourForceUTFArgumentFlag as the first argument and exit().
Assume UTF-8 and do what you have to...
Sounds shitty? That's because it is, but I can't think of any saner way of doing it.
One further note though:
If you are using UTF-8 as an encoding, stringWithCString:encoding: returns nil whenever it encounters non-ASCII characters in a C-String that is not encoded in UTF-8.)