UILabel text with unicode NSString - ios

This code shows correctly as Ecole with an accent on E:
NSString *test = #"\u00c9cole";
cell.detailTextLabel.text = test;
But when I get the string from my server sent as Json, I don't see E with an accent but rather the unicode \u00c9.
Code for getting Json string from server:
- (void) handleProfileDidDownload: (ASIHTTPRequest*) theRequest
{
NSMutableString *str = [[NSMutableString alloc] init];
[str setString:[theRequest responseString]];
[self preprocess:str]; //NSLog here shows str has the unicode characters \u00c9
}
- (void) preprocess: (NSMutableString*) str
{
[str replaceOccurrencesOfString:#"\n" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:#"\"" withString:#"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [str length])];
[str replaceOccurrencesOfString:#"\\/" withString:#"/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [str length])];
}
Now if I do,
cell.detailTextLabel.text = str;
I don't get the accent for E rather \u00c9
What am I doing wrong?

NSString *test = #"\u00c9cole";
is converted by the complier to the accented E.
In your JSON, the string \u00c9cole is a literal backslash-u-zero-zero-c-nine.
You can get the same behavior by escaping the backslash.
NSString *test2 = #"\\u00c9cole";
This will give you the same bad result, \u00c9cole.
To correctly unescape the JSON string, see Using Objective C/Cocoa to unescape unicode characters, ie \u1234.
I'm providing the link instead of an answer because there are three decent answers. You can choose the best one for your needs.

NSLog here shows str has the unicode characters \u00c9
From that, you can know that the JSON you receive doesn't actually have the letter É inside but the escape sequence \u00c9. So, you need to somehow unescape this string:
CFMutableStringRef mutStr = (CFMutableStringRef)[str mutableCopy];
CFRange rng = { 0, [mutStr length] };
CFStringTransform(mutStr, &rng, CFSTR("Any-Hex/Java"), YES);
Then you can use mutStr in your code.

Related

Remove "?" from NSString IOS

I am trying to remove all symbols from a string, it works fine with below code for all symbols except "?".
NSString *newString = self.titleString;
NSArray *characters = #[#"<", #"!", #"#", #"#", #"$", #"%", #"^", #"&", #"*", #"(", #")", #",", #"_", #"+", #"|", #">", #"?", #" "];
for (NSString *str in characters) {
newString = [newString stringByReplacingOccurrencesOfString:str withString:#""];
}
You can use stringByReplacingOccurrencesOfString with the regular expression option, NSRegularExpressionSearch:
NSString *output = [input stringByReplacingOccurrencesOfString:#"[<>!##$%^&*(),_+?| ]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];
You can also take advantage of other regular expression features, e.g. replace all non-letter characters:
NSString *output = [input stringByReplacingOccurrencesOfString:#"\\P{L}" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];
or not A-Z:
NSString *output = [input stringByReplacingOccurrencesOfString:#"[^a-zA-Z]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [input length])];
It just depends upon precisely what you're trying to achieve.
You can remove all characters in a single call using NSRegularExpression:
NSString *string = self.titleString;
NSError *error = nil;
// Prepare the regular expression that matches any of your characters
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"[<>!##$%^&*(),_+?| ]"
options:NSRegularExpressionCaseInsensitive
error:&error];
// Replace all matches with an empty string
string = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
You have to escape the ? like that: "\?". Otherwise it won't work properly. ? only means in regex stands for 0 or 1 occurences and so you have to say to objective-c that it is a real char you want to test.
If this is for editing user text you might want to consider using a union of more than one NSCharacterSet - this will help it be more language-friendly when you localize/internationalize your app.
NSString *myInputText = #"asd;jkfhals#$%^%$&1asldiguhd";
NSCharacterSet *nonAlphanumeric = [[NSMutableCharacterSet alphanumericCharacterSet] invert];
NSArray *parts = [myInputText componentsSeparatedByCharactersInSet:nonAlphanumeric];
NSArray *mySafeOutputText = [parts componentsJoinedByString:#""];
It's a little non-intuitive to use the components method, but unfortunately Apple doesn't provide a stringByReplacingCharactersInSet: method. :(

Extract substring from a string in iOS?

Is there any way to extract substring from a string like below
My real string is "NS09A" or "AB455A" but i want only "NS09" or "AB455" (upto the end of numeric part of original string).
How can i extract this?
I saw google search answers like using position of starting and endinf part of substring we can extract that ,But here any combination of "Alphabets+number+alphabets" .I need only " "Alphabets+number"
Perhaps not everybody will agree, but I like regular expressions. They allow to specify
precisely what you are looking for:
NSString *string = #"AB455A";
// One or more "word characters", followed by one or more "digits":
NSString *pattern = #"\\w+\\d+";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string
options:NSMatchingAnchored
range:NSMakeRange(0, [string length])];
if (match != nil) {
NSString *extracted = [string substringWithRange:[match range]];
NSLog(#"%#", extracted);
// Output: AB455
} else {
// Input string is not of the expected form.
}
Try This:-
NSString *str=#"ASRF12353FYTEW";
NSString *resultStr;
for(int i=0;i<[str length];i++){
NSString *character = [str substringFromIndex: [str length] - i];
if([character intValue]){
resultStr=[str substringToIndex:[str length]-i+1];
break;
}
}
NSLog(#"RESUKT STRING %#",resultStr);
I tested this code:
NSString *originalString = #"NS09A";
// Intermediate
NSString *numberString;
NSString *numberString1;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
[scanner scanUpToCharactersFromSet:numbers intoString:&numberString];
[scanner scanCharactersFromSet:numbers intoString:&numberString1];
NSString *result=[NSString stringWithFormat:#"%#%#",numberString,numberString1];
NSLog(#"Finally ==%#",result);
Hope it Help You
OUTPUT
Finally ==NS09
UPDATE:
NSString *originalString = #"kirtimali#gmail.com";
NSString *result;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *cs1 = [NSCharacterSet characterSetWithCharactersInString:#"#"];
[scanner scanUpToCharactersFromSet:cs1 intoString:&result];
NSLog(#"Finally ==%#",result);
output:
Finally ==kirtimali
Use NSScanner and the scanUpToCharactersFromSet:intoString: method to specify which characters should be used to stop the parsing. This could be in a loop with some logic or it could be applied in conjunction with setScanLocation: if you already have a method of finding the start of each section you want to extract.
When using scanUpToCharactersFromSet:intoString: you are looking for the next invalid character. It doesn't need to be a 'special' character (in a unicode sense), just a known set of characters that aren't valid for the content you want. So, you might use:
[[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet]
You can use - (NSString *)substringWithRange:(NSRange)aRange method on NSString class to get a substring extracted. Use NSMakeRange to create the NSRange object.

Remove parentheses without regex

I need to turn something like this
NSString *stringWithParentheses = #"This string uses (something special)";
Into this, programmatically.
NSString *normalString = #"This string uses";
The issue is I don't want to use all these weird libraries, regex, etc.
If you change your mind about the regex, here's a short, clean solution:
NSString *foo = #"First part (remove) (me (and ((me)))))) (and me) too))";
NSRegularExpression *expr = [NSRegularExpression regularExpressionWithPattern:#"\\(.*\\)" options:0 error:NULL];
NSString *bar = [expr stringByReplacingMatchesInString:foo options:0 range:NSMakeRange(0, foo.length) withTemplate:#""];
Everything between ( and ) gets removed, including any nested parentheses and unmatched parentheses within parentheses.
Just find the first open parentheses, note its index, find the closing one, note its index, and remove the characters between the indexes (including the indexes themselves).
To find the character use:
[string rangeOfString:#"("];
To remove a range:
[string stringByReplacingCharactersInRange:... withString:#""];
Here is a solution:
NSString* str = #"This string uses (something special)";
NSRange rgMin = [str rangeOfString:#"("];
NSRange rgMax = [str rangeOfString:#")"];
NSRange replaceRange = NSMakeRange(rgMin.location, rgMax.location-rgMin.location+1);
NSString* newString = str;
if (rgMin.location < rgMax.location)
{
newString = [str stringByReplacingCharactersInRange:replaceRange withString:#""];
}
It won't work on nested parentheses. Or multiple parentheses. But it works on your example. This is to be refined to your exact situation.
A way would be to find the position of the first occurrence of the '(' character and the last occurrence of the ')' character, and to build a substring by eliminating all the characters between these ranges. I've made an example:
NSString* str= #"This string uses (something special)";
NSRange r1=[str rangeOfString: #"("];
NSRange r2= [str rangeOfString: #")" options: NSBackwardsSearch];
NSLog(#"%#",[str stringByReplacingCharactersInRange: NSMakeRange(r1.location, r2.location+r2.length-r1.location) withString: #""]);

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

How to replace a case insensitive string in objective-c iphone?

I have a long string of some characters. I want to replace some chars with other chars.
For example
string1="Hello WORLD12";
string2="world";
string1= search string2 in string1 and replace it;
//need this method in objective c
string1="Hello world12";
If by case insensitive you mean the lower case replacement, Ken Pespisa has your answer, but if case insensitivity is about your search string you can do this:
[mystring stringByReplacingOccurrencesOfString:#"searchString" withString:#"replaceString" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mystring length])];
for more info see documentation of:
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
NSString *myString = #"select name SELECT college Select row";
[myString stringByReplacingOccurrencesOfString:#"select" withString:#"update" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [myString length])];
output: #"update name update college update row";
You can call the NSString method stringByReplacingOccurrencesOfString:withString:
NSString *string1 = "Hello WORLD12";
NSString *string2 = "world";
NSString *string3 = [string1 stringByReplacingOccurrencesOfString:#"WORLD" withString:string2];
Use NSRange to grab the replacing string and then usestringByReplacingOccurrencesOfString function to replace the characters in string.
NSString *string1 = "Hello WORLD12";
NSString *string2 = "world";
NSRange *range = [string1 rangeOfString:string2];
if (range.length > 0){
NSString *newString = [string1 substringFromIndex:range.location+6];
[string1 stringByReplacingOccurrencesOfString:newString withString:string2];
}

Resources