Search code examples
iosiphoneobjective-cnsstringcase-sensitive

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

Solution

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