最近踩了多个string的坑,嗯嗯!还是要抽时间总结一下的,顺便在后面写几个自己写的或者学习别人的算法
1、NSString的创建
//使用字面量创建字符串
NSString *string_0 = @"afeixiaohuozi";
//使用类方法创建字符串
NSString * string_1 = [NSString string];
string_1 = @"afeixiaohuozi";//字符串赋值
//创建一个字符串,并且将内容设置为string
NSString * string_2 = [NSString stringWithString:string_1];
//格式化创建字符串(按照格式输出)
NSString * string_3 = [NSString stringWithFormat:@"%@",string_1];
NSString * string_4 = [NSString stringWithFormat:@"hello %d %c",5,'A'];
//实例方法初始化
NSString *string_5 = [[NSString alloc] init];
//实例方法指定字符串
NSString *string_6 = [[NSString alloc] initWithString:string_3];
//实例方法创建字符串
NSString *string_7 = [[NSString alloc] initWithFormat:@"%@",string_4 ];
2、NSString的常用方法
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
NSString *string_7 = [NSString stringWithFormat:@"afeixiaohuozi"];
//获取字符串长度(有效字符长度,不包括'\0')
NSInteger length = [string_7 length];
//同样可以
NSInteger length = string_7.length;
//检测字符是否以指定内容开头
if ([string_7 hasPrefix:@"shan"]) {
NSLog(@"是的");
}
//检测字符串是否以指定内容结尾
if ([string_7 hasSuffix:@"long"]) {
NSLog(@"是的");
}
//字符串截取
//从哪个索引开始截取到字符串末尾(包含索引位置)
NSString *str0 = [string substringFromIndex:4];
//从字符串开头截取到哪个索引(不包含索引位置)
NSString *str1 = [string substringToIndex:8];
//截取一定范围(从下标3开始截取4个字符)
NSRange range = {3,4};
NSString *str2 = [string substringWithRange:range];
//关于NSRange的相关用法
//关于NSRange,请参考另一篇文章:添加链接
- (NSRange)rangeOfString:(NSString *)searchString;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
//NSStringCompareOptions相关链接
//用于字符串的检索
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
//不区分大小写比较
NSCaseInsensitiveSearch = 1,
//逐字节比较 区分大小写
NSLiteralSearch = 2,
//从字符串末尾开始搜索
NSBackwardsSearch = 4,
//搜索限制范围的字符串
NSAnchoredSearch = 8,
//按照字符串里的数字为依据,算出顺序。例如 Foo2.txt < Foo7.txt < Foo25.txt
NSNumericSearch = 64,
//忽略 "-" 符号的比较
NSDiacriticInsensitiveSearchNS_ENUM_AVAILABLE(10_5, 2_0) = 128,
//忽略字符串的长度,比较出结果
NSWidthInsensitiveSearchNS_ENUM_AVAILABLE(10_5, 2_0) = 256,
//忽略不区分大小写比较的选项,并强制返回 NSOrderedAscending 或者 NSOrderedDescending
NSForcedOrderingSearchNS_ENUM_AVAILABLE(10_5, 2_0) = 512,
//只能应用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比较方法,如果设置此项,可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
NSRegularExpressionSearchNS_ENUM_AVAILABLE(10_7, 3_2) = 1024
};
3、NSString比较
NSString *string_8 = @"afeixiaohozi";
NSString *string_9 = @"hai afeixiaohuozi";
//比较地址
//有一个例外,若是这两个字符串的内容是相同的,那么,这个 == 就是成立的,因为指针指向同一个地址
if (string_8 == string_9) {
}
//比较内容
if ([string_8 isEqualToString:string_9]) {
NSLog(@"一样的~~");
}else {
NSLog(@"不一样~~");
}
if ([string_8 compare:string_9] == NSOrderedSame) {
NSLog(@"相等");
}
else if ([string_8 compare:string_9] == NSOrderedAscending)
{
NSLog(@"升序");
}
else if ([string_8 compare:string_9] == NSOrderedDescending)
{
NSLog(@"降序");
}
//NSCaseInsensitiveSearch 忽略大小写(@“123”,@“0123”字符串比较)
NSComparisonResult result = [string_8 compare:string_9 options:NSCaseInsensitiveSearch];
if (result == NSOrderedSame) {
NSLog(@"相等");
}else if (result == NSOrderedAscending) {
NSLog(@"升序");
}else if (result == NSOrderedDescending) {
NSLog(@"降序");
}
}
//比较返回值
typedef NS_CLOSED_ENUM(NSInteger, NSComparisonResult) {
NSOrderedAscending = -1L, //升序 :前者大于后者
NSOrderedSame, //相等
NSOrderedDescending //降序 :前者小于后者
};
NSString的compare相关方法还有很多,没有一一进行使用,
嗯嗯,放在这里吧!万一啥时候去查询一下
#pragma mark *** String comparison and equality ***
/* In the compare: methods, the range argument specifies the subrange, rather than the whole, of the receiver to use in the comparison. The range is not applied to the search string. For example, [@"AB" compare:@"ABC" options:0 range:NSMakeRange(0,1)] compares "A" to "ABC", not "A" to "A", and will return NSOrderedAscending. It is an error to specify a range that is outside of the receiver's bounds, and an exception may be raised.
*/
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; // locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice.
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
- (NSComparisonResult)localizedCompare:(NSString *)string;
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
/* localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.
*/
- (NSComparisonResult)localizedStandardCompare:(NSString *)string API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
4、字符串拼接
//字符串拼接
NSString *string_10 = [string_7 stringByAppendingString:string_8];
NSString *string_11 = [NSString stringWithFormat:@"%@%@",string_7,string_8];
NSString *string_12 = [string_7 stringByAppendingFormat:@"-%@",string11];
//将数字字符串转换为数字
NSString *string_13 = @"123";
NSInteger integer = [string13 integerValue];
//字符串所有字符大写
NSString *string_14 = @"afeixiaohuozi";
NSString *str14 = [string_14 uppercaseString];
//字符串所有字符小写
NSString *string_15 = @"AFEIXIAOHUOZI";
NSLog(@"%@",[string_15 lowercaseString]);
//首字母大写
NSLog(@"%@",[string_14 capitalizedString]);
//替换
NSString *string_16 = @"文艺青年";
string_16 = [string_16 stringByReplacingOccurrencesOfString:@"文艺" withString:@"伪文艺"];
//删除原字符串中的所有指定字符,变为空
NSString * string_18 = [string_16 stringByReplacingOccurrencesOfString:@"文" withString:@""];
//从下标0开始替换2长度的字符
NSString *string_17 = [string_16 stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:@"真的是"];
NSRange rang = [string_16 rangeOfString:@"文艺"];
string_17 = [string_16 stringByReplacingCharactersInRange:rang withString:@"哈哈哈"];
//去掉两端空格
string_18 = [string_7 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//C语言字符串转化成OC字符串
NSString *str_20 = [NSString stringWithCString:"afeixiaohozi" encoding:NSUTF8StringEncoding];
//OC语言字符串转化成C字符串
const char *cStr = [string_8 cStringUsingEncoding:NSUTF8StringEncoding];
5、字符串拼接时候的坑
在修改一个bug的时候,平时用NSString字符串拼接总是失败(还是自己太粗心了)
NSString 的拼接方法是有返回值的,只有在返回值里面才是拼接好的字符串
- (NSString *)stringByAppendingString:(NSString *)aString;
- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//NSString 的拼接方法是有返回值的,只有在返回值里面才是拼接好的字符串
NSString *string_1 = nil;
NSString *string_2 = @"Afeixiaohiozi";
[string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1); //string_1 = (null)
//因为sring_1为空 结果返回值依旧是 nil
string_1 = [string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1);//string_1 = (null)
//so ,至少应该下面这样
NSString *string_1 = [NSString string] ;
NSString *string_2 = @"Afeixiaohiozi";
string_1 = [string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1);//string_1 = Afeixiaohiozi
//或者像这样
NSString *string_1 = @"I Am " ;
NSString *string_2 = @"Afeixiaohiozi";
string_1 = [string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1); //string_1 = I Am Afeixiaohiozi
//当然,也有没有返回值的拼接
//NSMutableString相关方法,也应该好好总结一下了
NSMutableString *nameStr = [NSMutableString string]
[nameStr appendString:string_2];
NSLog(@"nameStr = %@",nameStr);//nameStr = Afeixiaohiozi
//如果
NSMutableString *nameStr;
[nameStr appendString:string_2];
NSLog(@"nameStr = %@",nameStr); //nameStr = (null)
/*
不论是NSString 或者 NSMutableString 存储拼接后的字符串都是需要先申请空间的
*/
6、获取NSString中所有匹配子字符串的NSRange的array
NSString *string1=@"abcdefabcdefabcdefabcdefbcd";
NSString *string2=@"bcd";
NSArray *array=[string1 componentsSeparatedByString:string2];
NSMutableArray *arrayOfLocation=[NSMutableArray array];
int d=0;
for (int i = 0; i < array.count - 1; i++) {
NSString *string = array[i];
NSNumber *number = [NSNumber numberWithInt:d += string.length];
d += string2.length;
[arrayOfLocation addObject:number];
}
NSLog(@"%@",arrayOfLocation);
7、高亮规定字符串
//搜索匹配算法
//高亮中间的字符串
//NSString *aString = @"I am a string, not a astring, just a string";
- (NSMutableAttributedString *)newSetSearchResultStringColor:(NSString *)importString {
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:importString];
NSString *subString_1 = @"";
NSString *subString_2 = @"";
//获取subString_1的下标位置
NSArray *subString_1_array=[importString componentsSeparatedByString:subString_1];
NSMutableArray *arrayOfLocation1 = [NSMutableArray array];
int d = 0;
for (int i = 0; i < subString_1_array.count - 1; i++) {
NSString *string = subString_1_array[i];
NSNumber *number = [NSNumber numberWithInt:d += string.length];
d += subString_1.length;
[arrayOfLocation1 addObject:number];
}
//获取subString_2的下标位置
NSArray *subString_2_array=[importString componentsSeparatedByString:subString_2];
NSMutableArray *arrayOfLocation2 = [NSMutableArray array];
d = 0;
for (int i = 0; i < subString_2_array.count - 1; i++) {
NSString *string = subString_2_array[i];
NSNumber *number = [NSNumber numberWithInt:d += string.length];
d += subString_2.length;
[arrayOfLocation2 addObject:number];
}
//高亮中间string 删除标记string
NSInteger i = arrayOfLocation1.count - 1;
NSInteger j = arrayOfLocation2.count - 1;
for ( ;i >= 0 && j >= 0; i-- ,j--) {
NSInteger location_1 = [arrayOfLocation1[i] integerValue];
NSInteger location_2 = [arrayOfLocation2[j] integerValue];
//高亮的起始位置应该是在标记字符串后面
NSRange range = {location_1 + 4 , location_2 - location_1 - 4};
[resultString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(range.location,range.length)];
NSRange locationRange_1 = {location_1,4};
NSRange locationRange_2 = {location_2,5};
[resultString deleteCharactersInRange:locationRange_2];
[resultString deleteCharactersInRange:locationRange_1];
}
return resultString;
}
8、高亮所有匹配的字符
//NSString *inputString = @" a of American";
//NSString *showString = @"of I am office a of and American";
//inputString是输入的字符,要让showString中所有与inputString想匹配的单词高亮
- (NSMutableAttributedString *)showHeightLightLabel:(NSString*)inputString showLabel:(NSString*)showlabel
{
NSString *newInputLabel = [inputString lowercaseString];
NSString *newShowLabel = [showlabel lowercaseString];
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:showlabel];
NSCharacterSet *chartSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *chartStringArray = [newInputLabel componentsSeparatedByCharactersInSet:chartSet];
NSLog(@"%@",chartStringArray);
for (NSString* chart in chartStringArray) {
NSArray *showLabelArray = [newShowLabel componentsSeparatedByString:chart];
NSLog(@"%@",showLabelArray);
NSInteger location = 0;
for (NSString *showLabel in showLabelArray) {
location += showLabel.length;
if (location >= resultString.length) {
continue;
}
NSRange chartRange = NSMakeRange(location, chart.length);
[resultString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(chartRange.location,chartRange.length)];
location += chart.length;
}
}
return resultString;
}
//NSString *inputString = @" a of American";
//NSString *showString = @"of I am office a of and American";
//inputString是输入的字符,要让showString中所有与inputString想匹配的单词高亮
//需求中要求忽略某些文本开头的内容,所以引入ignoreString
//此算法可以兼容上面的高亮算法
- (NSMutableAttributedString *)showHeightLightLabel:(NSString*)inputString showLabel:(NSString*)showlabel withIgnoreString:(NSString *)ignoreString
{
NSString *newInputLabel = [inputString lowercaseString];
NSString *newShowLabel = [showlabel lowercaseString];
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:showlabel];
NSCharacterSet *chartSet = [NSCharacterSet whitespaceCharacterSet];
NSMutableArray *chartStringArray = [NSMutableArray arrayWithArray:[newInputLabel componentsSeparatedByCharactersInSet:chartSet]];
[chartStringArray removeObject:@"/"];
NSLog(@"%@",chartStringArray);
for (NSString* chart in chartStringArray) {
NSArray *showLabelArray = [newShowLabel componentsSeparatedByString:chart];
NSLog(@"%@",showLabelArray);
NSInteger location = 0;
for (NSString *showLabel in showLabelArray) {
location += showLabel.length;
if (location >= resultString.length || location < ignoreString.length) {
location += chart.length;
continue;
}
NSRange chartRange = NSMakeRange(location, chart.length);
[resultString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(chartRange.location,chartRange.length)];
location += chart.length;
}
}
return resultString;
}
注:本文也参考了一些文章,在此表示感谢