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

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

Related

Objective-C: Convert String to integer separated by colon

i have string value
NSString *str = #"12:15"
now how to convert it in to integer value??
i tryNSInteger i =[str integerValue];
but it's return only 12 and i want 1215.
Please suggest.
Thank you
A more generic approach would be to replace everything but the numeric values with an empty string like below:
NSString *str = #"12: a15xx";
str = [str stringByReplacingOccurrencesOfString:#"[^0-9]"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
NSLog(#"%d", str.integerValue); // prints 1215
a simple answer would be
NSString *str=#"12:15";
str = [str stringByReplacingOccurrencesOfString:#":" withString:#""];
NSInteger i =[str integerValue];
NSArray* arr = [#"12:15" componentsSeparatedByString: #":"];
NSString* strValue = [NSString stringWithFormat:#"%#%#",[arr objectAtIndex:0],[arr objectAtIndex:1]];
int value=(int)strValue;

Extract a String out of a specific set of strings

I have a text as:
sometext[string1 string2]someText
I want to retrieve string1 and string2 as separate strings from this text
How can i parse it in objective - c?
i have found the solution
NSArray *arrayOne = [prettyFunctionString componentsSeparatedByString:#"["];
NSString *parsedOne = [arrayOne objectAtIndex:1];
NSArray *arrayTwo = [parsedOne componentsSeparatedByString:#"]"];
NSString *parsedTwo = [arrayTwo objectAtIndex:0];
NSArray *arrayThree = [parsedTwo componentsSeparatedByString:#" "];
NSString *className = [arrayThree objectAtIndex:0];
NSString *functionName = [arrayThree objectAtIndex:1];
thanks anyways
Maybe something like this could work for you
NSString * string = #"sometext[string1 string2]sometext";
NSString * pattern = #"(.*)\[(.+) (.+)\](.*)"
NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult * match = [expression firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];
if (match) {
NSString * substring1 = [string substringWithRange:[match rangeAtIndex:2]];
NSString * substring2 = [string substringWithRange:[match rangeAtIndex:3]];
// do something with substring1 and substring2
}
You can Use this Simple Approach approach
NSString *str = #"sometext[string1 string2]someText";
NSInteger loc1 = [str localizedStandardRangeOfString:#"["].location;
NSInteger loc2 = [str localizedStandardRangeOfString:#"]"].location;
NSString *resultString = [str substringWithRange:(NSRange){loc1+1,loc2-loc1}];
NSArray *resultArry = [resultString componentsSeparatedByString:#" "];
result array will contain your required Reuslt
For completeness - if you are trying to extract strings out of a string with a known pattern, then an NSScanner is the way to go.
This goes through the string in one pass.
NSString *string = #"sometext[string1 string2]someText";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSString *str1;
NSString *str2;
[scanner scanUpToString:#"[" intoString:nil]; // Scan up to the '[' character.
[scanner scanString:#"[" intoString:nil]; // Scan the '[' character and discard it.
[scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &str1]; // Scan all the characters up to the whitespace and accumulate the characters into 'str1'
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:nil]; // Scan up to the next alphanumeric character and discard the result.
[scanner scanUpToString:#"]" intoString:&str2]; // Scan up to the ']' character, accumulate the characters into 'str2'
// Log the output.
NSLog(#"First String: %#", str1);
NSLog(#"Second String: %#", str2);
Which puts the output into the console of:
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] First String: string1
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] Second String: string2

IOS NSString get characters before '#"

for example i have string like this:
NSString *one = B3#This is the first string
NSString *two = 1#This is the second string
How can i get the "B3" and "1" Character only (using objective C)
Thanks..
Turns out this is one way to do it:
NSRange range = [one rangeOfString:#"#" options:NSBackwardsSearch];
NSString *newString = [one substringToIndex:range.location];
Thanks for all the answers.
NSString* one = #"B3#";
NSString* two = #"1#";
NSString* result = [one stringByReplacingOccurrencesOfString:#"#" withString:#""];
NSString* result_2 = [two stringByReplacingOccurrencesOfString:#"#" withString:#""];
//if you need to marge
NSString* tot = [NSString stringWithFormat:#"%#%#",result,result_2];

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.

UILabel text with unicode NSString

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.

Resources