欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-14 22:21:16
...
/*
 1.将可变字符串 @"When I was young, I loved a girl in neighbor class."中,从 young提取到girl。替换 成@"a teacher, I rather to teach student "。
 */
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        /*方法一*/
        //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);

        
    }
    
    return 0;
}