ios 字符串的插入删除查找与替换,删除空格
NSString *str1 = @"This is a example.";
NSMutableString *mstr = [[NSMutableString alloc] init]; //创建可变字符串
NSRange substr; //子字符串的范围
mstr = [NSMutableString stringWithString:str1];
//插入字符
[mstr insertString:@"very easy " atIndex:10];
//删除一些字符
[mstr deleteCharactersInRange:NSMakeRange(10,5)];
//查找并删除
substr = [mstr rangeOfString:@"easy "];
if (substr.location != NSNotFound) {
[mstr deleteCharactersInRange:substr];
}
//重新设置字符串
[mstr setString:@"This is string A"];
//替换字符串
[mstr replaceCharactersInRange:NSMakeRange(15, 1) withString:@"BBB"];
//查找第一个并替换
NSString *search = @"This is";
NSString *replace = @"An example of";
substr = [mstr rangeOfString:search];
if (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace];
}
//查找全部匹配的,并替换
search = @"a";
replace = @"X";
substr = [mstr rangeOfString:search];
while (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace];
substr = [mstr rangeOfString:search];
}
//删除空格
[string stringByReplacingOccurrencesOfString:@" " withString:@""]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。