PS:之前公司需要实现个,对字符串中关键字亮色处理。。所以弄了下相关的玩意
// NSString_CustomMethodString.h
// LabelAndString // // Created by Dale_Hui on 13-7-12. // Copyright (c) 2013年 Dale_Hui. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (StringTheCustomMethod) -(NSArray*)interceptionOfsubString:(NSString*)subStr; @end @implementation NSString(StringTheCustomMethod) /* 作用:解析字符串,得到子串所在位置数组 */ -(NSArray*)interceptionOfsubString:(NSString*)subStr { if (!subStr) { NSLog(@"ERROR:string=Nil"); return [NSArray arrayWithObjects:nil]; } NSMutableArray* testArray=[[NSMutableArray alloc]initWithCapacity:20]; int count=[[self componentsSeparatedByString:subStr]count]-1;
NSString * testStr=self; /*解析:录入数组*/ for (int i=0; i<count; i++) { NSRange tempRange=[testStr rangeOfString:subStr]; [testArray addObject:[NSValue valueWithRange:tempRange]]; if (i!=count-1) { tempRange.location=tempRange.location+tempRange.length; tempRange.length=testStr.length-subStr.length; testStr=[testStr substringFromIndex:tempRange.location]; } } NSMutableArray* requestArray=[[NSMutableArray alloc]initWithCapacity:20]; /*反向解析*/ for (int i=0; i<count; i++) { NSValue* value=[testArray objectAtIndex:i]; NSRange tempRange=value.rangeValue; for (int j=0; j<i; j++) { NSValue* jvalue=[testArray objectAtIndex:j]; NSRange jRange=jvalue.rangeValue; tempRange.location+=jRange.location+subStr.length; } [requestArray addObject:[NSValue valueWithRange:tempRange]]; } return [requestArray autorelease]; } @end