开发者

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

string开发者_运维百科1= 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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜