您的位置:首页 > 编程语言 > C语言/C++

iOS复习OC语言 NSString与NSArray 使用

2016-06-03 13:11 323 查看
@implementation ViewController

- (void)viewDidLoad {

    [super
viewDidLoad];

//    [self demo1]; //字符串的拼接、比较、搜索、大小写互换,判断开头与结尾、抽取、互换、剔除

//    [self demo2]; //动态字符串的增、删、查找、替换、判断

//    [self demo3]; //深浅copy

//    [self demo4];//遍历字符串、数组中内容查找

//    [self demo5]; //完整路径,省略路径,扩展名

//    [self demo6];//数组使用

    [self
demo7];//数组排序

}

#pragma mark -字符串的拼接、比较、搜索、大小写互换,判断开头与结尾、抽取、互换、剔除首尾

-(void)demo1{

    //赋值

    NSString *string =
@"Hello work!";

    NSString *string1 =
@"Hello work!";

    NSString *string2 =
@"Hello jianguo!";

    

    NSLog(@"string1 = %@ ;string2 = %@",string1,string2);

    

    //拼接

    NSString *string3 = [NSString
stringWithFormat:@"%@%@",string1,string2];

    NSLog(@"string3 = %@",string3);

    

    //比较

    if ([string1
isEqualToString:string2])
//区分大小写的

    {

        NSLog(@"YES");

    }else{

        NSLog(@"NO");

    }

    

    //compare

    BOOL result = ([string1
compare:string2] ==
NSOrderedSame); //NSOrderedSame判断两者内容是否相同

    result = [string1 compare:string] ==
NSOrderedSame;

    NSLog(@"result = %d",result);

    

    result = [string1 compare:string2] ==
NSOrderedAscending;
//按字母比较,string2大于string1为真

    NSLog(@"result = %d",result);

    

    result = [string1 compare:string2] ==
NSOrderedDescending;
//按字母比较,string2小于string1为真

    NSLog(@"result = %d",result);

    

    NSString *string4 =
@"hello work!";

    result = [string1 caseInsensitiveCompare:string4] ==
NSOrderedSame; //不考虑大小写比较

    NSLog(@"result = %d",result);

    

    result = [string1 compare:string2
options:NSCaseInsensitiveSearch |NSNumericSearch]
== NSOrderedSame;
//NSCaseInsensitiveSearch 不区分大小写;NSNumericSearch比较字符串的个数,不比较内容;NSLiteralSearch
区分大小写

    NSLog(@"NSCaseInsensitiveSearch result = %d",result);

    

    //大小写转换

    NSLog(@"%@:%@",string1,[string1
uppercaseString]);
//大写

    NSLog(@"%@:%@",string1,[string1
lowercaseString]);//小写

    NSLog(@"%@:%@",string4,[string4
capitalizedString]);//单词首字母大写

    

   
//在字符串中搜索字串

    NSRange rang = [string3
rangeOfString:string1];

    NSLog(@"string3 = %@,string1 = %@",string3,string1);

    NSLog(@"location = %ld,length = %ld",rang.location,rang.length);
//子串string1在string3中的位置和长度

    

    //hasPrefix 判断开头

    result = [string3 hasPrefix:string1];//判断string3是否以string1开头

    result = [string3 hasPrefix:string2];

    NSLog(@"hasPrefix result = %d",result);

    

    //hasSuffix  判断结尾

    result = [string3 hasSuffix:string2];

    NSLog(@"hasSuffix result = %d",result);

    

    //抽取字符串

    NSString *str1 = [string3
substringFromIndex:3];//从索引位置截取到最后

    NSLog(@"str1 = %@",str1);

    

    NSString *str2 = [string3
substringToIndex:8];
//从开始截取到索引位置

    NSLog(@"str2 = %@",str2);

    

    NSString *str3 = [string3
substringWithRange:NSMakeRange(6,
6)];

    NSLog(@"str3 = %@",str3);

    

    //汉字

    NSString *str=@"aBCdj34中国";

    NSLog(@"str=%@",str);

    NSLog(@"length=%lu",(unsigned
long)[str length]);//字符长度

    NSLog(@"中文占两个字符
length = %lu",(unsigned
long)[str
lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);//字符长度,中文占两个字符

    

    //剔除字符串

    NSString *ch1=@"  abj87w34 abTRE986  e1J6U";

    ch1=[ch1 stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceCharacterSet]]; 
//去除首尾空格

    NSLog(@"去除首尾空格ch1:%@",ch1);

    ch1 = [ch1 stringByTrimmingCharactersInSet:[NSCharacterSet
lowercaseLetterCharacterSet]];
//去除首尾小写字母

    NSLog(@"去除首尾小写字母ch1:%@",ch1);

    ch1 = [ch1 stringByTrimmingCharactersInSet:[NSCharacterSet
uppercaseLetterCharacterSet]];
//去除首尾大写字母

    NSLog(@"去除首尾大写字母ch1:%@",ch1);

    

    ch1 = [ch1 stringByTrimmingCharactersInSet:[NSCharacterSet
characterSetWithCharactersInString:@"87"]];//去除首尾指定字符串

    NSLog(@"去除首尾指定字符串ch1:%@",ch1);

    

   
//字符串与其它类型值互换

    int aa =
123;

    float bb =
3.0;

    NSString *aaStr = [NSString
stringWithFormat:@"%d---%f",aa+4,bb];
//数值->字符

    NSLog(@"aaStr:    %@",aaStr);

    

    NSArray *strrArray =
@[@"345",@"342.998"];

    

    int a = [strrArray[0]
intValue]; //字符->数值

    float b = [strrArray[1]
floatValue];

    NSLog(@"a= %d, b= %.2f",a,b);
//保留两位小数点

}

#pragma mark -动态字符串的增、删、查找、替换、判断

-(void)demo2{

    NSMutableString *s1 = [NSMutableString
stringWithFormat:@"%@",@"happy new year!"];

    NSMutableString *s2 = [NSMutableString
stringWithCapacity:60];
//定义字符串长度60

    

    [s1 appendString:@" baby!"];
//在末尾追加字符

    NSLog(@"s1 = %@",s1);

    

    [s2 appendFormat:@"%@",@"happy birthday!"];

    NSLog(@"s2 = %@",s2);

    

    [s2 insertString:@"Baby,"
atIndex:0];
//在指定位置插入字符

    NSLog(@"s2 = %@",s2);

    

    [s2 deleteCharactersInRange:NSMakeRange(10,
9)];//删除指定字符

    NSLog(@"s2 = %@",s2);

    

    [s2 replaceCharactersInRange:NSMakeRange(5,
5) withString:@"hello"];
//替换指定区域字符

    NSLog(@"s2 = %@",s2);

    

   
//参数1:目标替换值;参数2:替换成为的值;参数3:类型为默认:NSLiteralSearch;参数4:替换的范围

    [s2 replaceOccurrencesOfString:@"b"
withString:@"QQ"
options:NSLiteralSearch
range:NSMakeRange(0,
4)];

    NSLog(@"s2 = %@",s2);

    

    [s2 setString:@"hello,baby!"];
  //按新字符串替换原字符串

    NSLog(@"s2 = %@",s2);

}

#pragma mark -深浅copy

-(void)demo3{

    NSString *string1 =
@"Hello work!";

    NSString *ss1 = [string1
copy]; //浅copy

    NSLog(@"ss1:%@",ss1);

    

    string1 = @"happy new year!";

    NSLog(@"ss1:%@",ss1);

    

    NSMutableString *string2 = [string1
mutableCopy]; //深copy

    NSLog(@"string2:%@",string2);

    

    NSMutableString *string3 = [string2
copy];//深copy

    NSLog(@"string3:%@",string3);

    

    [string2 appendString:@"friend!"];

    NSLog(@"string2:%@;string3 = %@",string2,string3);

    

}

#pragma mark -遍历字符串

-(void)demo4{

    //遍历字符串

    NSString *string =
@"happy 12345 abc";

    NSMutableArray *strArray = [NSMutableArray
array];

    NSString *chr;

    for (int i =
0; i<string.length; i++) {

        chr =[string substringWithRange:NSMakeRange(i,
1)];

        [strArray addObject:chr];

    }

    NSLog(@"strArray:%@",strArray);

    

   
//倒序重组字符串

    NSMutableString *string1 = [NSMutableString
string];

    for (NSInteger i = [strArray
count]; i>0; i--) {

        [string1 appendString:strArray[i-1]];

    }

    NSLog(@"string1:%@",string1);

    

   
//数组内容查找、替换

    for (int i =
0; i<strArray.count; i++) {

        if ([strArray[i]
isEqualToString:@"a"]) {

            NSLog(@"strArray[%d]",i);
//位置查找

            strArray[i]=@"x";
//替换字母a

            NSLog(@"strArray[%d]:%@",i,strArray[i]);

        }

    }

    NSLog(@"strArray:%@",strArray);

}

#pragma mark -路径

-(void)demo5{

    //扩展路径

    NSString *Path =
@"~/NSData.txt";

    NSString *absolutePath = [Path
stringByExpandingTildeInPath];
//沙盒中完整路径

    NSLog(@"absolutePath:%@",absolutePath);

    NSLog(@"Path:%@",[absolutePath
stringByAbbreviatingWithTildeInPath]);//省略路径

    

    //文件扩展名

    NSLog(@"Extension:%@",[Path
pathExtension]);
//扩展名

}

//分割线

#pragma mark -

//分组标识

#pragma mark - 数组创建及基本使用

-(void)demo6{

    //遍历字符串

    NSString *string =
@"happy 12345 abc";

    NSMutableArray *strArray = [NSMutableArray
array];

    NSString *chr;

    for (int i =
0; i<string.length; i++) {

        chr =[string substringWithRange:NSMakeRange(i,
1)];

        [strArray addObject:chr];

    }

    NSLog(@"strArray:%@",strArray);

    

   
//获取指定下标的数组元素

    NSString *ssttrr = strArray[2];

    NSString *ssttrr2 = [strArray
objectAtIndex:2];

    NSLog(@"%@,%@",ssttrr,ssttrr2);

    

   
//判断数组中有无此元素

    BOOL isTure = [strArray
containsObject:@"a"];

    NSLog(@"包含a吗
%d",isTure);

    

    //获取索引值

    NSInteger index = [strArray
indexOfObject:@"p"];
//存在多个相同值时,返回第一个索引值

    NSLog(@"w的索引index:
%lu",index);

    NSLog(@"第一个元素:   %@",[strArray
firstObject]);  //获取第一个元素

    NSLog(@"最后一个元素: %@",[strArray
lastObject]);  //获取最后一个元素

    [strArray addObject:@"w"];//在最后加

    [strArray insertObject:@"789"
atIndex:8];//在指定位置插入

    [strArray setObject:@"66"
atIndexedSubscript:2];
//用新元素替换在指定位置元素

    NSArray *strArr =
@[@"4",@"9",@"7",@"8"];

    [strArray addObjectsFromArray:strArr];//在末尾追回数组

//    [strArray setArray:strArr]; //用新数组替换

    [strArray removeObject:@" "];
//删除空格元素

//    [strArray removeAllObjects];//删除所有元素

    [strArray replaceObjectAtIndex:9
withObject:@"ui"];
//修改指定位置元素

    [strArray exchangeObjectAtIndex:0
withObjectAtIndex:1]; 
//根据索引交换数组元素

    

    //快速遍历数组1

    int i =
0;

    for (NSString *str
in strArray) {

        NSLog(@"str %d =%@",i,str);

        i++;

    }

    

    //block方法遍历数组2 
按顺序遍历

    [strArray enumerateObjectsUsingBlock:^(id 
_Nonnull obj, NSUInteger idx,
BOOL * _Nonnull stop) {

        NSLog(@"obj:%@,索引idx:%ld",obj,idx);

        // 如果索引为6,就停止遍历

        if (idx ==
6) {

           *stop = YES; 
// 利用指针修改外面BOOL变量的值

        }

    }];

    //快速创建数组

    NSArray *arr = [@"1,2,3,4,5,6,7,8,9,0"
componentsSeparatedByString:@","];

    NSLog(@"arr:%@",arr);

    

    //倒序遍历 NSEnumerationReverse

    [arr enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id 
_Nonnull obj,
NSUInteger idx,
BOOL *
_Nonnull stop) {

        NSLog(@"NSEnumerationReverse obj:%@,索引idx:%ld",obj,idx);

    }];

    

    //同时遍历数组,无序  NSEnumerationConcurrent

    [arr enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id 
_Nonnull obj,
NSUInteger idx,
BOOL *
_Nonnull stop) {

        NSLog(@"NSEnumerationConcurrent obj:%@,索引idx:%ld",obj,idx);

    }];

   
//利用分隔符拼接数组所有元素

    NSString *ssAdd = [strArray
componentsJoinedByString:@"---"];

    NSLog(@"ssAdd:%@",ssAdd);

    

   
//利用分隔符切分成数组

    NSArray *newArray = [ssAdd
componentsSeparatedByString:@"--"];

    NSLog(@"newArray:%@",newArray);

    

   
// 将一个数组写入文件(生成的是一个xml文件)

    NSString *path =
@"/Users/liaojianguo/array.txt";

    [strArray writeToFile:path
atomically:YES];

   
// 从文件中读取数组内容(文件有严格的格式要求)

    NSArray *array2 = [NSArray
arrayWithContentsOfFile:path];

    NSLog(@"array2:%@",array2);

    

   
//让数组里所有对象都调用同print方法  注意见最下面

//    [strArr makeObjectsPerformSelector:@selector(printArr)];

//    [strArr makeObjectsPerformSelector:@selector(printArr:) withObject:self];

    

}

-(void)printArr:(NSString *)str{

    NSLog(@"print ok!%@",str);

}

#pragma mark - 数组排序

-(void)demo7{

    NSArray *sortArray = [[NSArray
alloc]
initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"12",@"12",@"20",@"28",@"",nil];

    //排序前

    NSLog(@"排序前:%@",sortArray);

    

    //第一种
用比较器排序数组 block

    NSComparator cmptr = ^(id obj1,
id obj2){

        if ([obj1
integerValue] > [obj2
integerValue])//数字比较

        {

            NSLog(@"NSOrderedDescending %ld",(long)(NSComparisonResult)NSOrderedDescending);

            return (NSComparisonResult)NSOrderedDescending;
//返回1

        }

        if ([obj1
integerValue] < [obj2
integerValue]) {

            NSLog(@"%ld",(NSComparisonResult)NSOrderedAscending);

            return (NSComparisonResult)NSOrderedAscending;
//返回-1

        }

        NSLog(@"NSOrderedSame %ld",(NSComparisonResult)NSOrderedSame);

        return (NSComparisonResult)NSOrderedSame;//返回0

    };

    

    NSComparator cmptr2 = ^(id obj1,
id obj2){

        if([[NSString
stringWithFormat:@"%@",obj1]
compare:[NSString
stringWithFormat:@"%@",obj2]
options:NSNumericSearch] >
0)//字符串比较

        {

            return (NSComparisonResult)NSOrderedDescending;

        }

        

        if([[NSString
stringWithFormat:@"%@",obj1]
compare:[NSString
stringWithFormat:@"%@",obj2]
options:NSNumericSearch] <
0)

        {

            return (NSComparisonResult)NSOrderedAscending;

        }

        

        return (NSComparisonResult)NSOrderedSame;

    };

    

    //第一种 sortedArrayUsingComparator

    NSArray *array1 = [sortArray
sortedArrayUsingComparator:cmptr];

    NSLog(@"array1排序后:%@",array1);

    

    NSArray *array111 = [sortArray
sortedArrayUsingComparator:cmptr2];

    NSLog(@"array111排序后:%@",array111);

    

    NSArray *array112 = [sortArray
sortedArrayUsingComparator:^NSComparisonResult(id 
_Nonnull obj1, id 
_Nonnull obj2) {

        if ([obj1
integerValue] > [obj2
integerValue])//数字比较

        {

            NSLog(@"NSOrderedDescending %ld",(long)(NSComparisonResult)NSOrderedDescending);

            return (NSComparisonResult)NSOrderedDescending;
//返回1

        }

        if ([obj1
integerValue] < [obj2
integerValue]) {

            NSLog(@"%ld",(NSComparisonResult)NSOrderedAscending);

            return (NSComparisonResult)NSOrderedAscending;
//返回-1

        }

        NSLog(@"NSOrderedSame %ld",(NSComparisonResult)NSOrderedSame);

        return (NSComparisonResult)NSOrderedSame;//返回0

    }];

    NSLog(@"array112排序后:%@",array112);

    

    //第二种
用函数排序数组 sortedArrayUsingFunction

    NSArray *array2 =[sortArray
sortedArrayUsingFunction:customSort
context:nil];

    NSLog(@"array2排序后:%@",array2);

    

    //第三种
使用描述符类 NSSortDescriptor

    [self
demo8];

}

//第二种
用函数排序数组

NSInteger customSort(id obj1,
id obj2,void* context)

{

    if ([obj1
integerValue] > [obj2
integerValue]) {

        return (NSComparisonResult)NSOrderedDescending;

    }

    

    if ([obj1
integerValue] < [obj2
integerValue]) {

        return (NSComparisonResult)NSOrderedAscending;

    }

    return (NSComparisonResult)NSOrderedSame;

}

//用于类排序

-(void)demo8{

    Student *student1 = [[Student
alloc]initWithName:@"kittey"
number:@"1001"
score:90];

    Student *student2 = [[Student
alloc]initWithName:@"meine"
number:@"1006"
score:94];

    Student *student3 = [[Student
alloc]initWithName:@"meiqi"
number:@"1002"
score:92];

    Student *student4 = [[Student
alloc]initWithName:@"snoopy"
number:@"1005"
score:94];

    Student *student5 = [[Student
alloc]initWithName:@"snoopy"
number:@"1008"
score:98];

    Student *student6 = [[Student
alloc]initWithName:@"snoopy"
number:@"1009"
score:94];

    

    NSArray *students =
@[student1,student2,student3,student4,student5,student6];

    

    // 1.先按照成绩进行排序

    // 这里的key写的是@property的名称

    NSSortDescriptor *scoreDesc = [NSSortDescriptor
sortDescriptorWithKey:@"score"
ascending:YES];

    // 2.再按照学号进行排序

    NSSortDescriptor *numberDesc = [NSSortDescriptor
sortDescriptorWithKey:@"number"
ascending:YES];

    // 3.再按照姓名进行排序

    NSSortDescriptor *nameDesc = [NSSortDescriptor
sortDescriptorWithKey:@"name"
ascending:YES];

   
// 按顺序添加排序描述器

    NSArray *descs =
@[scoreDesc,nameDesc,numberDesc];

    

    NSArray *array2 = [students
sortedArrayUsingDescriptors:descs];

    for (int i=0; i<array2.count;
i++) {

        NSLog(@"array2[%d]:%@    %@    %ld", i,[array2[i]
name],[array2[i]
number],[array2[i] score]);

    }

}

新建类

#import "ViewController.h"

@interface NSString (MD5Digest)

-(void)printArr:(id)data;

-(void)printArr;

@end

@implementation NSString (MD5)

-(void)printArr:(id)data{

    NSLog(@"print ok! %@,%@",self,data);

}

-(void)printArr{

    NSLog(@"print ok!");

}

@end

@interface
ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super
viewDidLoad];

    NSArray *strArr=
@[@"sdf",@"sd"];

    

   
//让数组里所有对象都调用同print方法

    [strArr makeObjectsPerformSelector:@selector(printArr)];

    [strArr makeObjectsPerformSelector:@selector(printArr:)
withObject:self];    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  objective-c