How convert string utf-8? - ios

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.

Related

how to add total number for NSString

I have a string like
NSString* str = #"[\"40.00\",\"10.00\",\"60.05\"]";
I need the total string amount "110.05"
You can proceed as follows:
1. Make an array out of the string. Since the array is in JSON format, you can do it like this:
NSString* str = #"[\"40.00\",\"10.00\",\"60.05\"]";
NSArray *stringArray = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
2. Convert the strings to double and add them up
double sum = 0;
for (NSString *value in stringArray) {
sum += [value doubleValue];
}
3. Convert the sum back to a NSString:
NSString *sumStr =[[NSString alloc] initWithFormat:#"%f", sum];
Note that approaches that convert NSString to double or float may cause rounding errors, to overcome this issue you must use NSDecimalNumber instead.
How about this?
float myTotal = 0;
for(int i=0;i<[_orderObj.itemArray count];i++) {
NSString *atemp=[_orderObj.itemArray valueForKeyPath:#"price"];
NSLog(#"title %#", atemp);
myTotal = myTotal + [atemp floatValue];
}
NSLog(#"final total==%f", myTotal);

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

Shuffling a greek word in iOS prints unknown symbols

I want to shuffle a string that contains Greek characters:
Here is my code:
- (void)shuffle {
NSLog(#"Will shuffle :%#",anagram2);
NSData* data = [anagram2 dataUsingEncoding:NSWindowsCP1253StringEncoding];
NSLog(#"after encoding :%#",anagram2);
NSString *someString = [[NSString alloc]initWithData:data encoding:NSWindowsCP1253StringEncoding];
NSLog(#"Greek word:%#",someString);
int length = anagram2.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
NSLog(#"Character:%#",letter);
[letters addObject:someLetter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
//NSLog(#"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
}
I can see the Greek word correctly. But the shuffling does not work. How can I extract each character and add it to a letters array. It works with English words but not with Greek ones, so I suppose that I should replace this:
NSString *letter = [NSString stringWithFormat:#"%c", [someString characterAtIndex:i]];
with something else.
The main problem seems to me that
[NSString stringWithFormat:#"%c":...]
works only with ASCII characters. You would have to use at least the "%C" format to make
it work with Unicode characters.
Also the conversion from NSString to NSData and back would fail as soon as you have any characters that are not available in the specified encoding.
The following method avoids all these problems and should work with arbitrary Unicode characters
(even with Emojis, which are internally represented as 2 UTF-16 characters):
NSString *string = #"螘位位维未伪 馃槃";
NSLog(#"Will shuffle: %#", string);
// Convert string to an array of (32 bit) Unicode characters:
NSMutableData *data = [[string dataUsingEncoding:NSUTF32BigEndianStringEncoding] mutableCopy];
uint32_t *letters = [data mutableBytes];
int length = [data length]/4; // The number of 32-bit Unicode characters
// Shuffle the Unicode characters:
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
uint32_t tmp = letters[i];
letters[i] = letters[value];
letters[value] = tmp;
}
// Create new string from the shuffled Unicode characters:
NSString *shuffled = [[NSString alloc] initWithData:data encoding:NSUTF32BigEndianStringEncoding];
NSLog(#"Shuffled: %#", shuffled);
Output:
Will shuffle: 螘位位维未伪 馃槃
Shuffled: 伪馃槃维位位 螘未

Converting an NSArray component into an integer or decimal number

I have a case where the data read from the CSV file in the app has to be converted into an integer, has to be plotted later. Currently it doesn't recognize when the data is saved as
int i=[[rows objectAtIndex:0] componentsSeparatedByString:#","];
This is the implemented code.
-(void)connection :(NSURLConnection *) connection didReceiveData:(NSData *)data{
[self serverConnect];
response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(response);
NSString *stripped1 = [response stringByReplacingOccurrencesOfString:#"\r" withString:#""];
NSArray *rows = [stripped1 componentsSeparatedByString:#"\n"];
NSArray *components;
for (int i=0;i<[rows count]; i++) {
if(i == 0 || [[rows objectAtIndex:i] isEqualToString:#""]){
continue;
}
components = [[rows objectAtIndex:i] componentsSeparatedByString:#","];
NSLog(#"data1:%# data2:%# data3:%#", [components objectAtIndex:0] ,[components objectAtIndex:1],[components objectAtIndex:2]);
}
data1, data2 and data3 are supposed to be integers.
Thanks a lot.
componentsSeparatedByString returns substrings, or instances of NSString.
components = [[rows objectAtIndex:i] componentsSeparatedByString:#","];
You just need to take each member of 'components' and get it's intValue, like so:
int myInt = [[components objectAtIndex:n] intValue];
NSArray and NSMutableArray can only contains objects. So get the integer value from it, use [object intValue]. If you need to add an integer to an array, create a NSNumber object from the integer and insert it. I know Rayfleck answered your question and i just want to point out the way how array works in iOS. Hope this helps.

Resources