NSString常用案例

NSString 常用案例在下面罗列:



//
// main.m
// NString
//
// Created by locksher on 15/6/29.
// Copyright (c) 2015年 locksher. All rights reserved.
//

import

int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");

    char *s = "c hello";
    NSString  *str = @"oc hello";
    
    
    //c->oc转换
    NSString *str1 = [NSString stringWithUTF8String:s];
    NSLog(@"str1=%@",str1);
    
    //oc->c转换
    NSLog(@"str2= %s",[str UTF8String]);
    
    
    //不需要自己释放内存的
    NSString *str3 = @"iOS";
    
    //需要自己释放内存
    NSString *str4 = [[NSString alloc] init];
    str4 = @"iOS";
    
    //格式化字符串
    int a = 10;
    int b = 20;
    
    
    NSString *str5 = [NSString stringWithFormat:@"a=%d b=%d",a,b];
    
    NSLog(@"str5=%@",str5);
    
    //拼接字符串
    NSString *str6 = [str5 stringByAppendingString:str3];
    
    NSLog(@"str6=%@",str6);
    
    
    //大小写转换
    NSString *str7 = @"ABCDEF";
    NSString *str8 = [str7 lowercaseString];
    NSLog(@"str8 = %@",str8);
    
    //判断前缀 后缀
    NSString *str10 = @"www.baidu.com";
    
    BOOL hasPreFix = [str10 hasPrefix:@"www."];
    if(hasPreFix){
        NSLog(@"有前缀");
    }
    else {
        NSLog(@"无前缀");
    }
    
    //后缀
    BOOL hasSuffix = [str10 hasSuffix:@".com"];
    if(hasSuffix){
        NSLog(@"有后缀");
    }
    else {
        NSLog(@"无后缀");
    }
    
    //判断两个字符串是否相同
    NSString  *str11 = @"1111";
    NSString *str12 = @"1111";
    if([str11 isEqualToString:str12]){
        NSLog(@"str11 相同 str12");
    }
    
    //分割
    //按照指定字符分割字符
    NSString  *str13 = @"a,b,c,d,e,f";
    NSArray   *strArray = [str13 componentsSeparatedByString:@","];
    
    for(NSString *str in strArray){
        NSLog(@"str = %@",str);
    }
    
    //按照范围截取字符串
    NSRange  range = NSMakeRange(1,5);
    NSString *str14 = [str13 substringWithRange:range];
    NSLog(@"str14 = %@",str14);
    
    //从某一位开始截取后面的字符串
    NSString *str15 = [str13 substringFromIndex:2];
    
    //从开头截取到某一位
    NSString *str16 = [str13 substringToIndex:7];
    
    
    //将字符串拆分每一个字符
    for(int i=0; i< [str13 length]; i++){
        NSLog(@"%c",[str13 characterAtIndex:i]);
    }
    
    //查找字符
    NSString  *str17 = @"ab cd ef gh ij ab";
    
    //查找指定字符串位置
    NSRange range1 = [str17  rangeOfString:@"ab"];
    
    NSLog(@"rang1.location: %ld range1.length:%ld",range1.location,range1.length);
    
    //替换
    NSString *str18 = @"hello str18, hello imoc";
    //替换某一个范围内容
    NSString *str19 =  [str18 stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:@"cc"];
    NSLog(@"%@",str19);
    
    
    
}
return 0;

}


你可能感兴趣的:(NSString常用案例)