OC中字符串的提取与替换-四种不同方法实现

/*
 1.将可变字符串 @"When I was young, I loved a girl in neighbor class."中,从 young提取到girl。替换 成@"a teacher, I rather to teach student "。
 */
     
        /*方法一*/
        //NSMutableString * str = @"When I was young, I loved a girl in neighbor class.";
        /*
        NSMutableString * str1 = [[NSMutableString alloc]initWithString:@"When I was young, I loved a girl in neighbor class."];
        [str1 replaceCharactersInRange:NSMakeRange(11, 21) withString:@"a teacher, I rather to teach student"];
        NSLog(@"%@",str1);
        */
        
        /**方法二  先删除 再插入*/
        /*
        NSMutableString * str1 = [[NSMutableString alloc]initWithString:@"When I was young, I loved a girl in neighbor class."];
        [str1 deleteCharactersInRange:NSMakeRange(11,22)];
        //NSLog(@"%@",str1);
        [str1 insertString:@"a teacher, I rather to teach student" atIndex:11];
        NSLog(@"%@",str1);
        */
        
        /*方法三*/
        /*
        NSMutableString * str1 = [[NSMutableString alloc]initWithString:@"When I was young, I loved a girl in neighbor class."];
        NSString * str2 = [str1 stringByReplacingOccurrencesOfString:@"young, I loved a girl" withString:@"a teacher, I rather to teach student"];
        NSLog(@"%@",str2);
        */
        
        /*方法四*/
        NSMutableString * str1 = [[NSMutableString alloc]initWithString:@"When I was young, I loved a girl in neighbor class."];
         NSMutableString * str2=[str1 stringByReplacingOccurrencesOfString:@"young, I loved a girl" withString:@""];
        [str2 insertString:@"a teacher, I rather to teach student" atIndex:11];
        NSLog(@"%@",str2);

posted @ 2015-10-10 11:14  努力努力再努力吧  阅读(783)  评论(0编辑  收藏  举报