From NSString to escaped chars in iOS - ios

I am not sure if I am asking the right question, please correct me if I'm wrong, but I've searched everywhere and I can't find an answer to help me with the following issue:
I have a NSString with the following content: "Björn Br. Björnsson"
and I need to get it to the following form: "Bj\u00f6rn Br. Bj\u00f6rnsson".
I've tried everything I found related on stackoverflow so far. If anyone has any idea how to get from ö type of characters to \u00f6 it would be awesome.
I have tried:
NSString *name = #"Björn Br. Björnsson";
NSString* string = [NSString stringWithCString:[name cStringUsingEncoding: NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
or
NSMutableString *string = [[NSMutableString alloc] initWithString:name];
const char *encoded = [string cStringUsingEncoding:NSASCIIStringEncoding];
or
NSData* nsData = [name dataUsingEncoding:NSUTF8StringEncoding];
const char* data = [nsData bytes];
NSUInteger len = nsData.length;
NSMutableString* hex = [NSMutableString string];
for(int i = 0; i < len; ++i)[hex appendFormat:#"%02X", data[i]];
or
const char * encodedStringName = [crewmemName cStringUsingEncoding:NSISOLatin1StringEncoding];
and many other..
Thanks in advance.

You can create a category on NSString and call this method, this will encode to your desired way
#implementation NSString (URLEncoding)
- (NSString *) stringByUrlEncoding{
return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)#"!*'();:#&;=+$,/?%#[]", kCFStringEncodingUTF8));
}
#end

NSString *name = #"Björn Br. Björnsson";
name =[name stringByReplacingOccurancesOfString:#"ö" withString:#"\u00f6"];
You may have to escape the backslash. Just type \\\ instead of \. But not sure about that.

Related

Assigning charAtIndex to stringWithCharacters gives invalid cast warning and bad access error

I'm trying to grab firstname and lastname from firstname+lastname.
int loop=0;
NSMutableString *firstname = [[NSMutableString alloc]init];
NSMutableString *fullName = [[NSMutableString alloc]initWithString:#"Anahita+Havewala"];
for (loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) {
[firstname appendString:[NSString stringWithCharacters:(const unichar *)[fullName characterAtIndex:loop] length:1]];
}
NSLog(#"%#",firstname);
I tried typecasting from unichar to const unichar* because characterAtIndex returns a unichar but stringWithCharacters accepts a const unichar.
This causes a cast from smaller integer type warning and the app crashes (bad access) when this line is encountered.
Why are string operations so complicated in Objective C?
You can easily get first name and last using componentsSeparatedByString: method.
NSMutableString *fullName = [[NSMutableString alloc]initWithString:#"Anahita+Havewala"];
NSArray *components = [fullName componentsSeparatedByString:#"+"];
NSString *firstName = components[0];
NSString *lastName = components[1];
Note: You need to do proper array bounds check. Also you can use NSScanner for the same purpose.
Try this out:
NSMutableString *firstname = [[NSMutableString alloc] init];
NSMutableString *fullName = [[NSMutableString alloc] initWithString:#"Anahita+Havewala"];
for (NSUInteger loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) {
unichar myChar = [fullName characterAtIndex:loop];
[firstname appendString:[NSString stringWithFormat:#"%C", myChar]];
}
NSLog(#"%#", firstname);

How to convert HEX to NSString in Objective-C j?

I have a NSString with hex string like "&# x62a;&# x631;&# x642;&# x628;" which means "ترقب".
Now I want to convert the hex string into another NSString object which shows "ترقب". How to do that ?
- (NSMutableString *) hextostring:(NSString *) str{
//ت
NSMutableString *string = [[NSMutableString alloc]init];
str = [str stringByReplacingOccurrencesOfString:#"&#" withString:#"0"];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"z;"];
NSArray *arr = [str componentsSeparatedByString:#";"];
for (int i =0; i<[arr count]; i++) {
if ([[arr objectAtIndex:i] isEqualToString:#"z"]) {
[string appendString:#" "];
} else {
unsigned x;
[[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
[string appendFormat:#"%C",(unichar)x];
}
}
NSLog(#"%#",string);
return string;
}
Your string looks like HTML escape sequences, except for the spaces after the #'s. If this is really what you have (check something isn't just displaying Unicode as escapes) then there is a myriad of ways to convert it. You can just process the string picking out the hex chars and producing UniChar values from them, etc.
If you want a high-level, maybe somewhat long-winded approach, you and try:
- (NSString *)decodeHTMLescapes:(NSString *)raw
{
NSString *nospaces = [raw stringByReplacingOccurrencesOfString:#" " withString:#""]; // one way to remove the spaces
const char *cString = [nospaces UTF8String]; // C string
NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
NSString *decoded = attributed.string; // and finally as plain text
return decoded;
}
That (a) strips the spaces, (b) creates a C string and (c) creates a byte buffer, all that so we can (d) interpret that byte buffer as HTML, and (e) finally gets the string back. The use of initWithBytesNoCopy:length:freeWhenDone: is to reduce the copying all this does.
Use it like:
NSString *raw = #"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(#"%# -> %#", raw, decoded);
HTH

How to encode the string in to "windows-1252" using ios?

The following string is working perfectly in android,please give me suggestion for encoding this in ios.
Android Example:String s = "hhh";
s.getBytes("Windows-1252");
A quick look at the docs for NSString would give you:
NSString *s = #"hhh";
NSData *data = [s dataUsingEncoding:NSWindowsCP1252StringEncoding];
uint_8 *bytes = [data bytes];
The equivalent code in iOS looks like this
NSString *str = #"hhh";
char buffer[100];
[str getCString:buffer maxLength:100 encoding:NSWindowsCP1252StringEncoding];

How convert string utf-8?

i've an NSString like this:
NSString *word = #"119,111,114,100"
So, what i want to do is to convert this NSString to word
So the question is, in which way can i convert a string to a word?
// I have added some values to your sample input :-)
NSString *word = #"119,111,114,100,32,240,159,145,141";
// Separate components into array:
NSArray *array = [word componentsSeparatedByString:#","];
// Create NSData containing the bytes:
NSMutableData *data = [[NSMutableData alloc] initWithLength:[array count]];
uint8_t *bytes = [data mutableBytes];
for (NSUInteger i = 0; i < [array count]; i++) {
bytes[i] = [array[i] intValue];
}
// Convert to NSString (interpreting the bytes as UTF-8):
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
Output:
word 👍
Try this:
NSString *word = #"119,111,114,100";
NSArray *array=[word componentsSeparatedByString:#","];
for (NSString *string in array) {
char character=[string integerValue];
NSLog(#"%c",character);
}
Output:
w
o
r
d
libicu it's an UTF8 library that supports a conversion from an array of bytes as stated here.
The thing is, it offers Java, C or C++ APIs, not obj-c.

How to convert NData populated with hex values to NSString

I have a NSdata object that is populated with a bunch of information thats formated in hex.. I am trying to convert it into its proper string representation but am struggling to have any success.
One thing I have tried is to simply put it into a NSString and then NSLog it with a special character identifier thingy.. forgot the word (%02x), However to do this I am encoding it to NSUTF16.. which i dont want to do.. I mearly want to see exactly whats the data I am getting looks like as a NSString.
The reason I am doing this is because I am having some issues with my encoding later on in my code and im not sure if its because the data I am receiving is incorrect or me stuffing it up at some point when I am handling it.
Any help would be appreciated.
You can get a string representation of your NSData like so:
NSData *data = (your data)
NSString *string = [NSString stringWithCString:[data bytes] encoding:NSUTF8StringEncoding];
Does that answer your question?
Maybe I haven't understood, but something like this:
NSData *yourData;
NSLog(#"%#", [yourData description]);
doesn't fit your need?
Give this a try -
-(NSString*)hexToString:(NSData*)data{
NSString *hexString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:#"%d", decimalValue];
}
return string;
}

Resources