Simple stringByReplacingOccurrencesOfString help issue - ios

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]]];

Related

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

Special Character to Original string - Objective C

I have tried the string(contain special character) to original String. The string received from service. I tried many codes. But i cant get the original String.
i tried the following code
// \U00e0\U00ae\U0089\U00e0\U00ae\U00b2\U00e0\U00ae\U0095\U00e0\U00ae\U00ae\U00e0\U00af\U008d
NSString *name2escaped = #"\\U00e0\\U00ae\\U0089\\U00e0\\U00ae\\U00b2\\U00e0\\U00ae\\U0095\\U00e0\\U00ae\\U00ae\\U00e0\\U00af\\U008d";
NSString *name2 = [NSString stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"name2 = %#", name2);
inputvalue.stringValue = name2;
NSLog (#"%#",name2);
Output prints: à®à®²à®à®®à¯
I worked in Mac OS X development 10.9 Mavericks
Service sometimes send chinese character also. Can anybody help me
As according to your requirement output should be Tamil or Chinese or English Language
Change NSNonLossyASCIIStringEncoding to NSUTF16StringEncoding :
NSString *name2escaped = #"\\U00e0\\U00ae\\U0089\\U00e0\\U00ae\\U00b2\\U00e0\\U00ae\\U0095\\U00e0\\U00ae\\U00ae\\U00e0\\U00af\\U008d";
NSString *name2 = [NSString stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSUTF16StringEncoding];
NSLog(#"name2 = %#", name2);
Output is : name2 = 屵〰攰屵〰慥屵〰㠹屵〰攰屵〰慥屵〰戲屵〰攰屵〰慥屵〰㤵屵〰攰屵〰慥屵〰慥屵〰攰屵〰慦屵〰㡤 –
I did it
My code is
- (NSString *) OrigninalString:(NSString *)getfilername
{
const char *c;
NSString *name2escaped = [NSString stringWithFormat:#"%#",getfilername];
NSString *string = [NSString
stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
c = [string cStringUsingEncoding:NSISOLatin1StringEncoding];
if (!c) {
c = [name2escaped cStringUsingEncoding:NSISOLatin1StringEncoding];
}
NSString *newString = [NSString stringWithCString:c encoding:NSUTF8StringEncoding];
c = nil;
string = nil;
return newString;
}

How to replace special characters in NSString with unknown index

I am trying to replace some characters with unknown index like this(i need to replace this Ă,Ŏ,Ĭ,ă,ŏ,ĭ and my input nsstring can be anything):
(void)repairText:(NSString *)textToRepair{`
NSString *pom = textToRepair;`
int pomNum = [pom length];
NSLog(#"Input nsstring: %#",pom);
for (int a = 0; a<pomNum; a++) {
NSString *pomChar, *pomChar2;
pomChar = [pom substringFromIndex:a];
pomChar2 = [pomChar substringToIndex:(1)];
NSLog(#"Char to repair: %#",pomChar2);
if ([pomChar2 isEqual: #"Ă"] || [pomChar2 isEqual:#"Ŏ"] || [pomChar2 isEqual:#"Ĭ"] || [pomChar2 isEqual:#"ă"] || [pomChar2 isEqual:#"ŏ"] || [pomChar2 isEqual:#"ĭ"]) {
if ([pomChar2 isEqual:#"Ă"]) {
NSLog(#"Wrong big a");
}
if ([pomChar2 isEqual:#"Ŏ"]) {
NSLog(#"Wrong big o");
}
if ([pomChar2 isEqual:#"Ĭ"]) {
NSLog(#"Wrong big i");
}
if ([pomChar2 isEqual:#"ă"]) {
NSLog(#"Wrong small a");
}
if ([pomChar2 isEqual:#"ŏ"]) {
NSLog(#"Wrong small o");
}
if ([pomChar2 isEqual:#"ĭ"]) {
NSLog(#"Wrong small i");
}
} else {
NSLog(#"Good");
}
}
pom = [textToRepair stringByReplacingOccurrencesOfString:#"•" withString:#" kulka "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"¥" withString:#" jen "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"£" withString:#" libra "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"€" withString:#" euro "];
[self synthesize:pom];
}
But I am having trouble with 'if'. If anyone know about this, please help in this regard.
NSString *str=#"ĂdsdaĬsd";
str=[str stringByReplacingOccurrencesOfString:#"Ă" withString:#""];
str=[str stringByReplacingOccurrencesOfString:#"Ĭ" withString:#""];
NSLog(#"%#",str);
O/p :dsdasd
NSString has functions to do that for you. dataUsingEncoding:allowLossyConversion: is the method you need.
From the documentation:
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.
Sample code:
NSString *str = #"á, é, í, ó, ú, ü, ñ";
NSData *asciiStringData = [str dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *finalString = [[NSString alloc] initWithData:asciiStringData
encoding:NSASCIIStringEncoding];
The final string will be : a, e, i, o, u, u, n
NSString * textToRepair = #"Your String";
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"•" withString:#"kulka"];
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"¥" withString:#"jen"]
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"£" withString:#"libra"];
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"€" withString:#"euro"];;
and now textToRepair is your output string with changes.
You can used this:
NSString * myString = #"Hello,";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];
NSLog(#"%#xx",newString);
I hope this is used full to you.

How to right pad a string using stringWithFormat

I would like to be able to right align a string using spaces. I have to be able to use the stringWithFormat: method.
So far I have tried the recommended format and it does not seem to work: [NSString stringWithFormat:#"%10#",#"test"].
I would expect this to return a string that has six spaces followed by "test" but all I am getting is "test" with no spaces.
It appears that stringWithFormat ignores the sizing requests of the %# format specifier. However, %s specifier works correctly:
NSString *test = #"test";
NSString *str = [NSString stringWithFormat:#"%10s", [test cStringUsingEncoding:NSASCIIStringEncoding]];
NSLog(#"'%#'", str);
This prints ' test'.
It's C style formatting. %nd means the width is n.
check following code.
NSLog(#"%10#",[NSString stringWithFormat:#"%10#",#"test"]);
NSLog(#"%#",[NSString stringWithFormat:#" %#",#"test"]);
NSLog(#"%10#", #"test");
NSLog(#"%10s", [#"test" cStringUsingEncoding:[NSString defaultCStringEncoding]]);
NSLog(#"%10d", 1);
NSString *str = #"test";
int padding = 10-[str length]; //6
if (padding > 0)
{
NSString *pad = [[NSString string] stringByPaddingToLength:padding withString:#" " startingAtIndex:0];
str = [pad stringByAppendingString:str];
}
NSLog(#"%#", str);

NSString replace unicode characters

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];

Resources