How to replace special characters in NSString with unknown index - ios

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.

Related

Objective C - How to compare string from the console

My code always returns "fail" for the following string comparison using isEqualToString. What is the correct way to compare strings coming from the console?
char buf[MAX_LENGTH];
fgets(buf, MAX_LENGTH, stdin);
NSString *s = [[NSString alloc] initWithUTF8String:buf];
NSLog(#"You typed %#", s);
NSString *n = #"exit";
if ([n isEqualToString:s]) {
NSLog(#"success!");
} else {
NSLog(#"fail");
}
The result of fgets contains "\n", So you need define your "n" as this:
NSString *n = #"exit\n";
Or remove the "\n" from "s":
NSString *s = [[NSString alloc] initWithUTF8String:buf];
s = [s stringByReplacingOccurrencesOfString:#"\n" withString:#""];

iOS - String capitalisation when followed by a numeric

I have a requirement where in first letter of all words in a sentence need to be capitalised. I achieved this through the below code
myString = [myString capitalizedString];
But there is an issue with this.. if the word starts with a numeric for eg "32abc", after capitalisation it changes to "32Abc". I need it to be "32abc".
Help would be appreciated.
Method 1
NSString *input = #"32abc";
/* get first char */
NSString *firstChar = [input substringToIndex:1];
/* remove any diacritic mark */
NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
/* create the new string */
NSString *capitalisedSentence = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];
Method 2 (Optimized)
NSString *input = #"32abc";
NSString *capitalisedSentence = [input stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[input substringToIndex:1] capitalizedString]];
Try this:
myString = [myString stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[myString substringToIndex:1] uppercaseString]];

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

Finding word in NSString and checking before and after character this word?

How to find word in NSString and check characters before and after this word?
"This pattern has two parts separated by the"
How to find tern and how to check the character before and after
Before word character:"t"
After word character:" "
You can use NSScanner to get indexes of these two characters.
Example:
NSString *string = #"tern";
NSScanner *scanner = [[NSScanner alloc] initWithString:#"This pattern has two parts separated by the"];
[scanner scanUpToString:string intoString:nil];
NSUInteger indexOfChar1 = scanner.scanLocation - 1;
NSUInteger indexOfChar2 = scanner.scanLocation + string.length;
You can also use a rangeOfString method:
Example:
NSRange range = [sourceString rangeOfString:stringToLookFor];
NSUInteger indexOfChar1 = range.location - 1;
NSUInteger indexOfChar2 = range.location +range.length + 1;
Then, when you have indexes, getting the characters is easy:
NSString *firstCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar1, 1)];
NSString *secondCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar2, 1)];
Hope this helps.
Here is an implementation using Regular Expressions
NSString *testString= #"This pattern has two parts separated by the";
NSString *regexString = #"(.)(tern)(.)";
NSRegularExpression* exp = [NSRegularExpression
regularExpressionWithPattern:regexString
options:NSRegularExpressionSearch error:&error];
if (error) {
NSLog(#"%#", error);
} else {
NSTextCheckingResult* result = [exp firstMatchInString:testString options:0 range:NSMakeRange(0, [testString length] ) ];
if (result) {
NSRange groupOne = [result rangeAtIndex:1]; // 0 is the WHOLE string.
NSRange groupTwo = [result rangeAtIndex:2];
NSRange groupThree = [result rangeAtIndex:3];
NSLog(#"[%#][%#][%#]",
[testString substringWithRange:groupOne],
[testString substringWithRange:groupTwo],
[testString substringWithRange:groupThree] );
}
}
Results:
[t][tern][ ]
Its better to get pre and post character in NSString to avoid handling of unicode characters.
NSString * testString = #"This pattern has two parts separated by the";
NSString * preString;
NSString * postString;
NSUInteger maxRange;
NSRange range = [testString rangeOfString:#"tern"];
if(range.location == NSNotFound){
NSLog(#"Not found");
return;
}
if (range.location==0) {
preString=nil;
}
else{
preString = [testString substringWithRange:NSMakeRange(range.location-1,1)];
}
maxRange = NSMaxRange(range);
if ( maxRange >=testString.length ) {
postString = nil;
}
else{
postString = [testString substringWithRange:NSMakeRange(range.location+range.length, 1)];
}

How to convert a currency string to number

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

Resources