20150610之OC中字符串NSString的操作

在学习OC的时候,我们经常会使用字符串中的一些库函数,一下就列出OC中经常使用的NSString的库方法的使用.NSString定义的对象 是不能修改的,即指针指向的内存中的内容不可修改,而指针的指向可以改变.它和NSMutableString不同.方法使用如下:
//
//  main.m
//  IOS150610_ObjectiveC_NSStringOperation
//
//  Created by Peng Junlong on 15/6/10.
//  Copyright (c) 2015年 Peng Junlong. All rights reserved.
//

//****************************
//*                          *
//*     NSString操作         *
//*                          *
//****************************

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //@property (readonly) NSUInteger length;
        NSString *str1 = @"Hello China";
        
        //*****************字符串提取*************************
        
        //求字符串长度
        NSUInteger len = [str1 length];
        NSLog(@"len = %li",len);                        //结果:len = 11
        
        //获取字符串指定位置的字符
        //- (unichar)characterAtIndex:(NSUInteger)index;
        unichar ch = [str1 characterAtIndex:4];
        NSLog(@"ch = %C",ch);                           //结果:ch = o
                                                        //%C打印unichar字符,%c打印ASCII码字符
        
        //从传入的下标的位置提取子串到字符串结束
        //- (NSString *)substringFromIndex:(NSUInteger)from;
        NSString *subStr1 = [str1 substringFromIndex:4];
        NSLog(@"SubStr1 = %@",subStr1);                 //结果: SubStr1 = o China
        
        //从开始提取子串到指定位置,不包含下标位置字符
        //- (NSString *)substringToIndex:(NSUInteger)to;
        NSString *subStr2 = [str1 substringToIndex:7];
        NSLog(@"subStr2 = %@",subStr2);                 //结果:subStr2 = Hello C
        
        //提取指定范围内的字符串
//        typedef struct _NSRange {
//            NSUInteger location;
//            NSUInteger length;
//        } NSRange;
//        - (NSString *)substringWithRange:(NSRange)range;
        NSRange range = {6,5};
        NSString *subStr3 = [str1 substringWithRange:range];
        NSLog(@"subStr3 = %@",subStr3);                 //结果:subStr3 = China
        
//        NS_INLINE NSRange NSMakeRange(NSUInteger loc, NSUInteger len) {
//            NSRange r;
//            r.location = loc;
//            r.length = len;
//            return r;
//        }
        //NSMakeRange()构建一个NSRange变量
        NSString *subStr4 = [str1 substringWithRange:NSMakeRange(2, 5)];
        NSLog(@"subStr4 = %@",subStr4);                 //subStr4 = llo C
        
        //*****************字符串比较(比较字符的编码)*************************
        
        NSString *str2 = [NSString stringWithCString:"Hello World上海" encoding:NSUTF8StringEncoding];
        NSString *str3 = [NSString stringWithUTF8String:"Hello World中国"];
        NSString *str4 = [NSString stringWithUTF8String:"hello world中国"];
        
        //- (NSComparisonResult)compare:(NSString *)string;
        //typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};
        //NSComparisonResult是枚举类型
        NSComparisonResult result = [str2 compare:str3];
        if (result == NSOrderedAscending) {             //结果:str2 < str3
            NSLog(@"str2 < str3");
        }
        else if (result == NSOrderedDescending)
        {
            NSLog(@"str2 > str3");
        }
        else
        {
            NSLog(@"str2 = str3");
        }
        
        //以大小写不敏感的方式进行比较
        //- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
        NSComparisonResult result1 = [str3 caseInsensitiveCompare:str4];
        if (result1 == NSOrderedAscending) {            //结果:str3 = str4
            NSLog(@"str3 < str4");
        }
        else if (result == NSOrderedDescending)
        {
            NSLog(@"str3 > str4");
        }
        else
        {
            NSLog(@"str3 = str4");
        }
        
        //判断两个字符串是否相等
        //  - (BOOL)isEqualToString:(NSString *)aString;
        BOOL ret = [str3 isEqualToString:str4];
        if (ret == YES) {                               //结果:str3 != str4
            NSLog(@"str3 == str4");
        }
        else
        {
            NSLog(@"str3 != str4");
        }
        
        //判断字符串是否以某个字符串开头(前缀)
        // - (BOOL)hasPrefix:(NSString *)aString;
        BOOL ret1 = [@"www.baidu.com" hasPrefix:@"www"];
        NSLog(@"ret1 = %d",ret1);                       //结果:ret1 = 1
        //判断字符串是否以某个字符串结尾(后缀)
        //- (BOOL)hasSuffix:(NSString *)aString;
        BOOL ret2 = [@"www.baidu.com" hasSuffix:@"com"];
        NSLog(@"ret2 = %d",ret2);                       //结果:ret2 = 1
        
        //判断是否包含子串(10.10MAC OS)
        BOOL ret3 = [@"www.hao123.com" containsString:@"hao"];
        NSLog(@"ret3 = %d",ret3);                       //结果:ret3 = 1
        
        //*****************查找子串*************************
        /* These methods return length==0 if the target string is not found. So, to check for containment: ([str rangeOfString:@"target"].length > 0).  Note that the length of the range returned by these methods might be different than the length of the target string, due composed characters and such.
         */
        //- (NSRange)rangeOfString:(NSString *)aString;
        //- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
        
        //正序查找
        NSString *str5 = [[NSString alloc] initWithFormat:@"%s","hello world Chinaworld"];
        NSRange range1 = [str5 rangeOfString:@"world"];
        if (range1.location == NSNotFound) {            //结果:location = 6 lenght = 5
                                                        //如果找不到对应的子字符串,则返回long类型对应的最大值
                                                        //从左往右查找,返回查找到的的第一个
            NSLog(@"没有找到子字符串 notFound = %lu",NSNotFound);
        }
        else
        {
            NSLog(@"location = %lu lenght = %lu",range1.location,range1.length);
        }
        
        //倒序查找
        range1 = [str5 rangeOfString:@"world" options:NSBackwardsSearch];   //添加一个参数选项 options:NSBackwardsSearch
        NSLog(@"location = %lu lenght = %lu",range1.location,range1.length);//从右往左查找    结果:location = 17 lenght = 5
        
        //*********************子串追加*************************
        
        //- (NSString *)stringByAppendingString:(NSString *)aString;
        //并不是直接在原字符串的末尾追加字符串,而是利用传入的字符串及原字符串创建一个新的字符串
        NSString *str6 = @"Hello";
        NSString *str7 = [str6 stringByAppendingString:@" World"];          //一定不要忘记接收返回值
        NSLog(@"str6 = %@",str6);                       //结果:str6 = Hello   ,str6没有变
        NSLog(@"str7 = %@",str7);                       //结果:str7 = Hello World
        
        //格式化追加字符串
        //- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
        NSString *str8 = @"China Shang";
        NSLog(@"str8 = %p",str8);                       //结果:str8 = 0x100002440
        str8 = [str8 stringByAppendingFormat:@"%d%s",1234," Hello"];
        NSLog(@"str8 = %@",str8);                       //结果:str8 = China Shang1234 Hello
        NSLog(@"str8 = %p",str8);                       //结果:str8 = 0x10020e1c0
        
        //把字符串对象转化成整型,浮点型...
        /* The following convenience methods all skip initial space characters (whitespaceSet) and ignore trailing characters. NSScanner can be used for more "exact" parsing of numbers.
         
        @property (readonly) double doubleValue;
        @property (readonly) float floatValue;
        @property (readonly) int intValue;
        @property (readonly) NSInteger integerValue NS_AVAILABLE(10_5, 2_0);
        @property (readonly) long long longLongValue NS_AVAILABLE(10_5, 2_0);
        @property (readonly) BOOL boolValue NS_AVAILABLE(10_5, 2_0);  // Skips initial space characters (whitespaceSet), or optional -/+ sign followed by zeroes. Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9. It ignores any trailing characters.
         */
        int a = [@"1234" intValue];
        NSLog(@"a = %d",a);                             //结果:a = 1234
        float b = [@"1234" intValue];
        NSLog(@"b = %f",b);                             //结果:b = 1234.000000
        
        //返回公共前缀子串
        NSString *str9 = [@"www.baidu.com" commonPrefixWithString:@"www.hao123.com" options:NSLiteralSearch];
        NSLog(@"str9 = %@",str9);                       //结果:str9 = www.
        
        //*********************大小写转换*************************
        /* The following three case methods perform the canonical (non-localized) mappings. They are suitable for programming operations that require stable results not depending on the user's locale preference.  For localized case mapping for strings presented to users, use their corresponding methods with locale argument below.
         */
        //@property (readonly, copy) NSString *uppercaseString;
        //@property (readonly, copy) NSString *lowercaseString;
        //@property (readonly, copy) NSString *capitalizedString;
        
        //把小写字母转化成大写字母
        NSString *str10 = [@"baidu中国" uppercaseString];
        NSLog(@"str10 = %@",str10);                     //结果:str10 = BAIDU中国
        
        //把大写字母转化成小写字母
        NSString *str11 = [@"BAIDU中国" lowercaseString];
        NSLog(@"str11 = %@",str11);                     //结果:str11 = baidu中国
        
        //把每个单词的首字母转换成大写
        NSString *str12 = [@"baidu zhongguo中国" capitalizedString];
        NSLog(@"str12 = %@",str12);                     //结果:str12 = Baidu Zhongguo中国
        
        //*********************字符串替换*************************
        
        /* Replace all occurrences of the target string with replacement. Invokes the above method with 0 options and range of the whole string.
         
        - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement ;
         */
        NSString *str13 = @"hello world china hello world china";
        str13 = [str13 stringByReplacingOccurrencesOfString:@"hello" withString:@"你好"];
        NSLog(@"str13 = %@",str13);                     //结果:str13 = 你好 world china 你好 world china
        
        //替换指定范围内的字符
        /* Replace characters in range with the specified string, returning new string.
         
        - (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement ;
        */
        NSString *str14 = @"hello world shanghai zhongguo";
        str14 = [str14 stringByReplacingCharactersInRange:NSMakeRange(12, 8) withString:@"anhui"];  //替换这个范围NSMakeRange(12, 8)里的字符
        NSLog(@"str14 = %@",str14);                     //结果:str14 = hello world anhui zhongguo
        
        //把OC的字符串对象转换成C字符串
        //@property (readonly) __strong const char *UTF8String NS_RETURNS_INNER_POINTER;	// Convenience to return null-terminated UTF8 representation
        NSLog(@"%s",[@"Hello China" UTF8String]);       //结果:Hello China
        
        //*********************用网址的内容生成OC字符串对象*************************
        /* These use the specified encoding.  If nil is returned, the optional error return indicates problem that was encountered (for instance, file system or encoding errors).
         */
        //- (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
        //- (instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
        //+ (instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
        //+ (instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
        NSURL *url = [[NSURL alloc] initWithString:@"http://www.baidu.com"];        //一定要加http://才能获取网址的内容
        NSString *urlContent = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];    //nil空指针
        NSLog(@"%@",urlContent);
        
        //使用文本内容生成OC字符串对象
        NSString *fileContent = [NSString stringWithContentsOfFile:@"/Users/qianfeng/Desktop/123.txt" encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@",fileContent);
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值