字符串常用整理

//創建字符串
    NSString *Str1 = [NSString stringWithFormat:@"the number is %d",5];
    
    //長度和索引字符
    NSLog(@"%d",[Str1 length]);
    printf("%c",[Str1 characterAtIndex:2]);
    
    //與c字符串相互轉換
    printf("%s\n",[Str1 UTF8String]);
    printf("%s\n",[Str1 cStringUsingEncoding:NSUTF8StringEncoding]);
    NSLog(@"%@",[NSString stringWithCString:"Hello world"
                                   encoding:NSUTF8StringEncoding]);
    
    //將字符串寫入文件和從文件讀取字串
    NSString *Str2 = @"Hello world";
    NSError *error;
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file.txt"];
    
    [Str2 writeToFile:path
           atomically:YES
             encoding:NSUTF8StringEncoding
                error:&error];
    
    NSString *outString = [NSString stringWithContentsOfFile:path
                                                    encoding:NSUTF8StringEncoding
                                                       error:&error];
    
    //將字符串轉換為數組
    NSString *Str3 = @"One Two Three";
    NSArray *wordArray = [Str3 componentsSeparatedByString:@" "];
    
    //取出索引子字符串
    NSString *sub1 = [Str3 substringToIndex:7];
    NSString *sub2 = [Str3 substringFromIndex:3];
    
    //根據範圍生成子字符串
    NSRange r;
    r.location = 4;
    r.length = 2;
    NSString *sub3 = [Str3 substringWithRange:r];
    
    //搜索字符串
    NSRange searchRange = [Str3 rangeOfString:@"Two"];
    if(searchRange.location != NSNotFound)
        NSLog(@"Range Location:%d length:%d",searchRange.location,searchRange.length);
    
    //替換字串
    NSString *replaced = [Str3 stringByReplacingOccurrencesOfString:@" "
                                                         withString:@"*"];
    
    //改變大小寫
    NSLog(@"%@",[Str3 uppercaseString]);//大寫
    NSLog(@"%@",[Str3 lowercaseString]);//小寫
    NSLog(@"%@",[Str3 capitalizedString]);//首字母大寫

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值