//
// main.m
// OC语言学习
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *str1 = @"This is string A";
NSString *search, *replace;
NSMutableString *mstr;
NSRange substr;
//从不可变字符串创建可变字符串
mstr = [NSMutableString stringWithString:str1];
NSLog(@"%@",mstr); //This is string A
//插入字符
[mstr insertString:@" mutable" atIndex:7];
NSLog(@"%@",mstr); // This is mutable string A
//插入末尾进行有效拼接
[mstr insertString:@" and string B" atIndex:[mstr length]];
//直接使用 appendString
[mstr appendString:@" and string C"];
NSLog(@"%@",mstr); //This is mutable string A and string B and string C
//根据范围删除 子字符串
[mstr deleteCharactersInRange:NSMakeRange(16, 13)];
NSLog(@"%@",mstr); //This is mutable string B and string C
//查找是否存在,如果存在就删除
substr = [mstr rangeOfString:@"string B and "];
if (substr.location != NSNotFound) {
[mstr deleteCharactersInRange:substr];
}
//直接设置为可变字符串
[mstr setString:@"This is string A"];
NSLog(@"%@",mstr); //This is string A
//替换一些字符
[mstr replaceCharactersInRange:NSMakeRange(8, 8) withString:@"a mutable string"];
NSLog(@"%@",mstr); //This is a mutable string
//查找和替换
search = @"This is";
replace = @"An example of";
substr = [mstr rangeOfString:search];
if (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace];
NSLog(@"%@",mstr); //An example of a mutable string
}
//查找和替换所有匹配项
search = @"a";
replace = @"x";
substr = [mstr rangeOfString:search];
while (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace];
substr = [mstr rangeOfString:search];
}
NSLog(@"%@",mstr); // An exxmple of x mutxble string
}
return 0;
}
可变字符串的基本操作
最新推荐文章于 2022-07-28 15:35:47 发布