I'w working with a server and I have to download text to my iOS application. Only problem : all characters like "é à ç" are replaced by "\U008" for example. Is there a way to fix this problem, to replace this code by the right character ?
Try to parse the received text (textToParse variable) with this one:
NSString *encodedString = textToParse;
NSString *decodedString = [NSString stringWithUTF8String:[encodedString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
I tested some encodings and NSMacOSRomanStringEncoding fit well.
My test was:
NSString *encodedString = [NSString stringWithCString:"Você realmente deseja sair da área restrita" encoding:NSMacOSRomanStringEncoding];
Remember that the message has to be a C-string ("string") and not an NSString(#"string")
You can get character buffer and validate each character like so:
- (NSString *) removeUnicode:(NSString *) unicodeString {
NSUInteger len = [unicodeString length];
unichar buffer[len+1];
[unicodeString getCharacters:buffer range:NSMakeRange(0, len)];
unichar okBuffer[len+1];
int index = 0;
for(int i = 0; i < len; i++) {
if(buffer[i] < 128) {
okBuffer[index] = buffer[i];
index = index + 1;
}
}
NSString *removedUnicode = [[NSString alloc] initWithCharacters:okBuffer length:index];
return removedUnicode;
}
or you can use this sample:
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:[NSCharacterSet alphanumericCharacterSet]] invertedSet];
stringWithOutUnicode = [[stringWithUnicode componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
and you can create your own valid character set and get not allowed characters
NSString *allowedCharacters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString: allowedCharacters] invertedSet];
Related
I have a long string, and I would like to remove a specific hexadecimal character from it.
NSString * myString = #"longlongstringwithcharacters\"ofallsorts\"";
Any suggestions?
The hex character I am after is 08, that corresponds to backspace. How can I use code like the following to substitute it? I have no idea on how to represent 08 in a string:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:#" " withString:#""];
EDIT:
I will try to clarify a bit more what I am trying to do..
I am trying to remove all occurrences of a character that corresponds to 08 hex from the string that I receive as payload.
The payload is in a string format and I found out the character by using Xcode debugger and view the hex codes of the string as there was an invalid character when trying to covert the NSData corresponding to the string to a NSDictionary.
I am not sure how to phrase the problem correctly..
- (NSString *)stringFromHexString:(NSString *)hexString {
// The hex codes should all be two characters.
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:#"%c", decimalValue];
}
return string;
}
Try this code...This will help you to convert Hex to string
NSString * str = #"68656C6C6F";
NSMutableString * newString = [[[NSMutableString alloc] init] autorelease];
int i = 0;
while (i < [str length])
{
NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
int value = 0;
sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
[newString appendFormat:#"%c", (char)value];
i+=2;
}
this will help u to convert Hex to NSString
This code worked for me:
NSString * dataString = message.payloadString;
NSString * wrongCharacter = [[NSString alloc] initWithFormat:#"%c", (char)0x08];
dataString = [dataString stringByReplacingOccurrencesOfString:wrongCharacter withString:#""];
I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];
I have the following string:
R$1.234.567,89
I need it to look like: 1.234.567.89
How can i do this?
This is what i tried:
NSString* cleanedString = [myString stringByReplacingOccurrencesOfString:#"." withString:#""];
cleanedString = [[cleanedString stringByReplacingOccurrencesOfString:#"," withString:#"."]
stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]];
It works, but I think there must be a better way. Suggestions?
If your number always after $, but you got more characters before it, you can make it like this:
NSString* test = #"R$1.234.567,89";
NSString* test2 = #"TESTERR$1.234.567,89";
NSString* test3 = #"HEllo123344R$1.234.567,89";
NSLog(#"%#",[self makeCleanedText:test]);
NSLog(#"%#",[self makeCleanedText:test2]);
NSLog(#"%#",[self makeCleanedText:test3]);
method is:
- (NSString*) makeCleanedText:(NSString*) text{
int indexFrom = 0;
for (NSInteger charIdx=0; charIdx<[text length]; charIdx++)
if ( '$' == [text characterAtIndex:charIdx])
indexFrom = charIdx + 1;
text = [text stringByReplacingOccurrencesOfString:#"," withString:#"."];
return [text substringFromIndex:indexFrom];
}
result is:
2013-10-20 22:35:39.726 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.728 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.731 test[40546:60b] 1.234.567.89
If you just want to remove the first two characters from your string you can do this
NSString *cleanedString = [myString substringFromIndex:2];
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: α😄άλλ Εδ
I want to replace some "ilegal" characters from a string to another "legal" characters, I have this code:
- (NSString *) quitarTildes:(NSString *)aStr
{
NSString *aux = aStr;
NSString *invalid = #"áéíóúÁÉÍÓÚñÑ";
NSString *valid = #"aeiouAEIOUnN";
for (int i = 0; i < [invalid length]; i++)
[aux stringByReplacingOccurrencesOfString: [NSString stringWithFormat:#"%c",[invalid characterAtIndex:i]]
withString: [NSString stringWithFormat:#"%c",[valid characterAtIndex:i]]];
NSLog(#"%#",aux);
return aux;
}
And all ilegal character still there...
NSString *test = #"Hólá, Ésto es una prueba.";
test = [self quitarTildes: test];
NSLog, response:
2013-04-04 08:58:52.896 GeoRuta_v1[1960:907] Hólá, Ésto es una prueba.
From the documentation:
stringByReplacingOccurrencesOfString:withString: Returns a new string
in which all occurrences of a target string in the receiver are
replaced by another given string.
-(NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
So:
aux = [aux stringByReplacingOccurrencesOfString: [NSString stringWithFormat:#"%c",[invalid characterAtIndex:i]]
withString: [NSString stringWithFormat:#"%c",[valid characterAtIndex:i]]];
A perhaps simpler solution to achieve your goal:
NSString *test = #"Hólá, Ésto es una prueba. - áéíóúÁÉÍÓÚñÑ";
test = [test stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:NULL];
NSLog(#"%#", test);
Output:
Hola, Esto es una prueba. - aeiouAEIOUnN
One. You're using the wrong format specifier for characterAtIndex:. That method returns unichar and not char (for obvious reasons). You have to use %C (capital C).
Two. You're returning the original string, and not replacing its characters.
NSMutableString *tmp = [aStr mutableCopy];
// ...
[tmp replaceOccurrencesOfString:[NSString stringWithFormat:#"%C", [invalid characterAtIndex:i]]
withString:[NSString stringWithFormat:#"%C", [valid characterAtIndex:i]]];