iPhone - Convert NSString encoding from WindowsCP1251 to UTF8 - iphone

how can I have this conversion from NSWindowsCP1251StringEncoding to UTF-8?
I had several attempts but no one worked as it should. My last try was:
NSData *dt = [mystr dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = [NSString alloc] initWithData:dt encoding:NSWindowsCP1251StringEncoding];
The result of str is unreadable. Did anyone encounter anything similar?

I think you were so close:
// Convert it back to CP1251
NSData *dt = [mystr dataUsingEncoding:NSWindowsCP1251StringEncoding];
// Now load it as UTF8
NSString *str = [NSString alloc] initWithData:dt encoding:NSUTF8StringEncoding];

Related

NSUTF8StringEncoding or stringWithUTF8String

I am having some issues in dealing with characters in NSStrings.
I read a XML file converted to NSData, it is okay, but when I transfer the "Element name" it has not converted to UTF-8.
I've tried here are some examples of the site, but with no success.
My Code is -
NSString * S = [NSString stringWithFormat: # "%#", D];
S = [S stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
Try this..
NSString *url = S;
NSString *check=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
check=[check stringByReplacingOccurrencesOfString:#"%0A" withString:#""];

iPhone: strange output when casting nsdata to nsstring

I get a NSData object in return after decrypting a payload with aes128:
NSData *returnData = [ciphertext AES128DecryptWithKey:keyData withIV:ivData];
I get the following hex output when i try to NSLog this:
<2db88b73 d84599a1 5779c736 09c975b7 92750cf2 d11cb41b 19f13781
4401bc57 b2ad96c8 402e3ccf 851c0219 00aec76b>
I then try to setting it as NSString:
[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
When using NSLog() on the string i get "(null)" as output.
Can someone tell me why and where i should look for the problem?
Collided with the same issue some time ago, found the answer here.
If the data is not null-terminated, you should use -initWithData:encoding:
NSString* newStr = [[[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding] autorelease];
If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
(If you have ARC enabled, remove the -autorelease call.)

passing a UInt32 into a NSData object returns (null)

I am trying to pass a NSNumber into a UInt32, which is working.. Then I am trying to stuff that UInt32 into a NSData object.. however this is where things get abit funky...
when I try to write whats in that NSData object out to a string its returning (null).
This is what my code looks like, I think it has something to do with the way I am passing CACHE_VALUE into requestCacheData.. but I am not totally sure why.
// Use the correctly returned cache number
UInt32 CACHE_VALUE = [cacheNumber intValue];
NSLog(#"%lu", CACHE_VALUE); //gives me the correct integervalue
NSData * requestCacheData = [[NSData alloc] initWithBytes:&CACHE_VALUE length:sizeof(CACHE_VALUE)];
NSString *myString = [[NSString alloc] initWithData:requestCacheData encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString); //outputs (null)
any help would be appreciated.
you can't turn the NSData to a right NSString that NSData do not contain a right string content.
in your case , your NSData just contain a binary unsigned int,
what do you suppose to get ?
NSString* str= #"a NSString";
NSData* requestCacheData =[str dataUsingEncoding:NSUTF8StringEncoding];
NSString *myString = [[NSString alloc] initWithData:requestCacheData encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString);
you may get the right ouput,
but if you want to turn a UINT to NSString
just
NSString *str = [[[NSString alloc] initWithFormat:#"%u",CACHE_VALUE] autorelease];

Can not read file in XCODE 4.2, worked in 4.0?

I have upgraded from XCODE 4 to 4.2 and now i have problems.
The following code worked pre 4.2 to read the file in "filePath":
// Fill myString with questions from the .txt file and then read .txt file
NSString *filePath = whatFile;
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
// Load array
NSArray* myArray = [myString componentsSeparatedByString:#"\r"];
NSLog (#"\n \n Number of elements in myArray = %i", [myArray count]);
With 4.2 the "initWithContentsOfFile" in the following code line is deprecated:
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath];
...and should be replaced with the below according to the manual:
NSString *myString = [NSString stringWithContentsOfFile:filePath encoding: NSUTF8StringEncoding error:&err];
and i can not get this to read the records in the same file by replacing the code line. BTW, i have defined the &err.
When i NSLog myString i get (null).
I am getting a bit desperate to solve this and would very much appreciate any help.
Cheers
NSLog the err variable if there is an error. Also NSLog filePath.
Perhaps the encoding is not UTF-8, are you sure about the encoding?
The best non-UTF-8 encoding bet is NSMacOSRomanStringEncoding which supports 8-bit characters.
Try :
NSError* error = nil;
NSStringEncoding encoding;
NSString *fileContent = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
If that does not works, try in your code : NSASCIIStringEncoding
The file probably doesn't contain a UTF8 encoded string. See apple's documentation, which has an example of reading a file where you do not know the encoding: Reading data with an unknown encoding
You need to use the [string|init]WithContentsOfFile:usedEncoding:error method, and if that fails there are a few more things you can try before finally presenting an error message to the user (for example, try reading it as an NSAttributedString).
For example, you could do this:
// Fill myString with questions from the .txt file and then read .txt file
NSString *filePath = whatFile;
NSStringEncoding encoding;
NSError *error;
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
if (!myString) {
myString = [[NSString alloc] encoding:NSUTF8StringEncoding error:&error]
}
if (!myString) {
myString = [[NSString alloc] encoding:NSISOLatin1StringEncoding error:&error]
}
if (!myString) {
NSLog(#"error: %#", error);
return;
}
// Load array
NSArray* myArray = [myString componentsSeparatedByString:#"\r"];
NSLog (#"\n \n Number of elements in myArray = %i", [myArray count]);

NSString - how to go from "ÁlgeBra" to "Algebra"

Does anyone knows hoe to get a NSString like "ÁlgeBra" to "Algebra", without the accent, and capitalize only the first letter?
Thanks,
RL
dreamlax has already mentioned the capitalizedString method. Instead of doing a lossy conversion to and from NSData to remove the accented characters, however, I think it is more elegant to use the stringByFoldingWithOptions:locale: method.
NSString *accentedString = #"ÁlgeBra";
NSString *unaccentedString = [accentedString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
NSString *capitalizedString = [unaccentedString capitalizedString];
Depending on the nature of the strings you want to convert, you might want to set a fixed locale (e.g. English) instead of using the user's current locale. That way, you can be sure to get the same results on every machine.
NSString has a method called capitalizedString:
Return Value
A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
NSString *str = #"AlgeBra";
NSString *other = [str capitalizedString];
NSLog (#"Old: %#, New: %#", str, other);
Edit:
Just saw that you would like to remove accents as well. You can go through a series of steps:
// original string
NSString *str = #"ÁlgeBra";
// convert to a data object, using a lossy conversion to ASCII
NSData *asciiEncoded = [str dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
// take the data object and recreate a string using the lossy conversion
NSString *other = [[NSString alloc] initWithData:asciiEncoded
encoding:NSASCIIStringEncoding];
// relinquish ownership
[other autorelease];
// create final capitalized string
NSString *final = [other capitalizedString];
The documentation for dataUsingEncoding:allowLossyConversion: explicitly says that the letter ‘Á’ will convert to ‘A’ when converting to ASCII.
Here's a step by step example of how to do it. There's room for improvement, but you get the basic idea......
NSString *input = #"ÁlgeBra";
NSString *correctCase = [NSString stringWithFormat:#"%#%#",
[[input substringToIndex:1] uppercaseString],
[[input substringFromIndex:1] lowercaseString]];
NSString *result = [[[NSString alloc] initWithData:[correctCase dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding] autorelease];
NSLog( #"%#", result );