提取字符串中子串所在的位置-Objective-c(字符串提取关键词位置)

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







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值