How to covert std::string to NSString? ,why the result is garbled?I use lldb command po ,look at the console ,the red arrow,the _data display correct string?Why?
std::string resultString = getResult();
NSString *str= [NSString stringWithCString:resultString.c_str() encoding:NSUTF8StringEncoding];
but the str is garbled,like
May be here issue is with string encoding. I have done little test on this input string and found some result on that.
Here I have use complex string "\x18\xa4\tp\x01" which you shown in your log. From the result I conclude that NSUTF8StringEncoding encoding string is not working with above string.
Here is code:
+ (void) stringTest {
std::string *resultString = new std::string("\x18\xa4\tp\x01");
NSString *str= [NSString stringWithCString:resultString->c_str() encoding:NSUTF8StringEncoding];
NSString *str2= [NSString stringWithCString:resultString->c_str() encoding:NSASCIIStringEncoding];
NSString *str3= [NSString stringWithCString:resultString->c_str() encoding:[NSString defaultCStringEncoding]];
NSLog(#"str :%#",str);
NSLog(#"str2 :%#",str2);
NSLog(#"str3 :%#",str3);
}
And a reference image for log:
Here you can see that NSUTF8StringEncoding returns nil string and other encoding gives a result. I'm not sure which encoding scheme is valid for your string. If we know that encoding scheme for resultString string then we can get more accurate result here.
Related
I am trying to implement an app where I would like to show some text in Spanish format. For example I would like to show "España" but in my label it shows "Espa√ɬ±a" and also it changes the text for some of other text.
How to get rid of these. If anybody could help. Thanks.
Edit: When i am getting my response it logs that Below result
Message = (
"Espa\U221a\U00c9\U00ac\U00b1a:1.3\U221a\U00c7\U00ac\U00a2/min"
);
But when i extract the value according to key from Dictionary it shows
España:1.3¢/min
It means when i am getting the value from dictionary it cant do proper decoding.
how to resolve this. Any idea..?
First convert your response String to NSData using NSUTF8StringEncoding encoding, then again convert the same data to finalString like below.
NSString *string = #"España"; //Your response String goes here
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *finalString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
lblTemp.text = finalString;
UPDATE 1
I think there is some error from your response, Please see below
NSString *string = #"Nu\\u0161a Florjan\\u010di\\u010d";
NSString *finalString = [NSString
stringWithCString:[string cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"finalString = %#", finalString);
Output of above code is,
finalString = Nuša Florjančič
UPDATE 2
If you want output string like "España", your desired response should be "Espa\u00F1a", Find below,
NSString *string = #"Espa\\u00F1a";
NSString *finalString = [NSString
stringWithCString:[string cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"%#",finalString);
Output is España
In Java code, this code can get hex string "efbfbc";
new String((((char)-4 )+ "").getBytes("utf8"),"iso8859-1")
How can implement it in iOS Objective-C?
by byte -4, get hex string "efbfbc";
NSString *string = #"efbfbc";
char converted[([string length] + 1)];
NSString* str = [[NSString alloc]
initWithCString: converted encoding: NSISOLatin1StringEncoding];
NSLog(#"Your result string: %#",str);
I got below result:
Check out this AppleDoc for more information about intiWithCString method. It will give you a clear idea.
i have solve the problem.
unichar asciiChar = -4;
NSString *string = [NSString stringWithCharacters:&asciiChar length:1];
string = [NSString stringWithCString:[string UTF8String] encoding: NSISOLatin1StringEncoding];
now , string hex is "efbfbc"
thanks everyone.
I am very new to Objective-C.
I want to get the encoded content for a NSString. In java I can do that as follows,
String str = "https://www.google.co.in/#q=ios+sqlite+crud+example";
String encodedParam = URLEncoder.encode(str, "UTF-8");
I am using http://www.tutorialspoint.com/compile_objective-c_online.php to test the codes posted in stackoverflow. There is no solution yet. I know its trivial one. Struggling to find a way though.
tried with following function, and it says following error while compile,
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
Error,
sh-4.3$ gcc `gnustep-config --objc-flags` -L/usr/GNUstep/System/Library/Libraries -lgnustep-base -lobjc *.m -o main
main.m: In function 'main':
main.m:7:14: error: 'urlEncodeUsingEncoding' undeclared (first use in this function)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
^
main.m:7:14: note: each undeclared identifier is reported only once for each function it appears in
main.m:7:36: error: expected ';' before ':' token
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
Edit as per the answers,
Suggested by Patrick, I used the code as follows,
NSString *storedURL = #"google.com/?search&q=this";
NSString *urlstring = [NSString stringWithFormat:#"http://%#/",storedURL];
NSURL *url = [NSURL URLWithString:urlstring];
NSError *error = nil;
NSStringEncoding encoding;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
NSLog (my_string);
Nothing printed in console... Is it my NSLog is right?
Suggested by lightwolf, my code is looks like below,
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSString *encodedParam = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog (encodedParam);
it prints the log, but value is same as the str..... not encoded... I want this str as
https%3A%2F%2Fwww.google.co.in%2F%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
If you want to encode a specific range of characters you chould use
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSString *encodedParam = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
NSLog (#"%#", encodedParam);
Note the invertedSet; In that way, you are encoding all characters except the set specified (all alphanumeric ones)
The result is
https%3A%2F%2Fwww%2Egoogle%2Eco%2Ein%2F%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
If you want to use a specific set of characters you should use
NSString *str = #"https://www.google.co.in/#q=ios+sqlite+crud+example";
NSCharacterSet* set = [NSCharacterSet characterSetWithCharactersInString:#"!*'();#&=+$,?%#[]"];
NSString *encodedParam = [str stringByAddingPercentEncodingWithAllowedCharacters:[set invertedSet]];
NSLog (#"%#", encodedParam);
In this case I intentionally missed / and : so the result is
https://www.google.co.in/%23q%3Dios%2Bsqlite%2Bcrud%2Bexample
Maybe this is what you want
NSString *str = #"<html><head><title>First</title></head><body><p>Parsed HTML into a doc.</p></body></html>";
NSString *encodedParam = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You have to encode only the params, not the entire URL of course
I'm trying to encrypt/decrypt an NSString and return the original string in the end. Here's how I convert the string to a data object:
NSData *string_data = [string dataUsingEncoding:NSUTF8StringEncoding];
And after that data has been encrypted/decrypted I want it back to the original string by doing:
NSString *to_string = [NSString stringWithCString:[decrypted_data bytes] encoding:NSUTF8StringEncoding];
The encoding seems to match, but I still get a null when I try to print out to_string to the console. I've tried all sorts of encoding settings. It doesn't seem to work.
Use:
NSString *to_string = [[NSString alloc] initWithData:string_data encoding:NSUTF8StringEncoding];
It is not safe to use stringWithCString because the bytes buffer you get from NSData is not guaranteed to be null-terminated.
I have one app in that I have support four Languages. In that When I am login with Chinese User name at that time it shows me Response like this ..
[{"0":"41","intid":"41","1":"\u8a00\u3046","varfirstname":"\u8a00\u3046","2":"\u8a00\u3046","varlastname":"\u8a00\u3046","3":"\u5730","varusername":"\u5730","4":"abc#gmail.com","varemailid":"abc#gmail.com","5":"qwert","varpassword":"qwert","6":"12345","varmobileno":"12345","7":"Enable","mobileMessage":"Enable","8":"","varphoneno":"","9":"Enable","enumstatus":"Enable","10":"2013-01-30","date_insert":"2013-01-30","11":"2013-01-30","date_edit":"2013-01-30","12":"1.38.28.36","varipaddress":"1.38.28.36"}]
I want to Show "varfirstname" to UITextfield Text . But I am not getting any Text when I print it in NSLog .
NSLog(#"Text is === %#",textfname,text);
How can I decode this Text? And show it on UITextfield or UILabel.
I just searched it and found one of the useful Answer from here.
It's natural that Chinese and Japanese characters don't work with ASCII string encoding. If you try to escape the string by Apple's methods, which you definitely should to avoid code duplication, store the result as a Unicode string. Use one of the following encodings:
NSUTF8StringEncoding
NSUTF16StringEncoding
NSShiftJISStringEncoding (not Unicode, Japanese-specific)
UPDATE
For Example you can encode Decode your chinese String like below:
NSString * test = #"汉字马拉松是";
NSString* encodedString =[test stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"====%#",encodedString);
OUTPUT IS:
%E6%B1%89%E5%AD%97%E9%A9%AC%E6%8B%89%E6%9D%BE%E6%98%AF
Then Decode it like:
NSString* originalString =[encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"====%#",originalString);
OUTPUT IS:
汉字马拉松是
NSString *abc = #"\u8a00\u3046";
NSLog(#" %# " , [NSString stringWithUTF8String:[abc UTF8String]]);
and if you use json :
NSString *html = #"\u8a00\u3046";
NSData *jsonData = [html dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#" %# " , [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
they all output "言う" I think it is Japanese