字元串
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyNwETN1kDM0ETOwgDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
前言
字元串其實就是我們最常用的的NSString,但是它通過oc中為字元串設定的很多方法,使它成為一個應用範圍很廣的基本資料類型,我們可以用今天的知識做出簡單的語言屏蔽系統,文字輸入密碼檢測系統等小程式。而首先,我們要知道字元串是一個執行個體對象,也就是引用類型,例如NSString *str=[NSString new];中,其實str本質就是一個指針。是以我們首先要學習如何将OC和C中的基本資料類型轉換成對象,才可以更加友善我們學習字元串。
封裝|拆包
OC中的封裝、拆包基本資料類型
NSValue / NSNumber
功能:
将OC和C中的基本資料類型轉換成執行個體對象,即值類型 轉換 引用類型
C和OC中 常用的資料類型
int a=;
float b=;
double c=;
char d='a';
bool flag=YES;
// CGPoint point={3, 4)};
// CGSize size={5,6};
// CGRect rect={3, 4, 5, 6};
// NSRange range={10,3};
CGPoint point=CGPointMake(, );
CGSize size=CGSizeMake(, );
CGRect rect=CGRectMake(, , , );
NSRange range=NSMakeRange(, );
NSEdgeInsets edgeInsets=NSEdgeInsetsMake(, , , );
封裝
NSValue / NSNumber
NSNumber:NSValue
其中NSValue 可以将CGPoint、CGSize、CGRect、NSRange、NSEdgeInsets轉換成對象:
NSValue *pointVa=[NSValue valueWithPoint:point];
NSValue *sizeVa=[NSValue valueWithSize:size];
NSValue *rectVa=[NSValue valueWithRect:rect];
NSValue *rangeVa=[NSValue valueWithRange:range];
NSValue *edgeVa=[NSValue valueWithEdgeInsets:edgeInsets];
其中NSNumber 可以将int、float、double、char、bool等基本資料類型轉換成對象:
NSNumber *intNum=[NSNumber numberWithInt:a];
NSNumber *floatNum=[NSNumber numberWithFloat:b];
NSNumber *doubleNum=[NSNumber numberWithDouble:c];
NSNumber *charNum=[NSNumber numberWithChar:d];
NSNumber *boolNum=[NSNumber numberWithBool:flag];
拆包
int a1=[intNum intValue];
float b1=[floatNum floatValue];
double c1=[doubleNum doubleValue];
char d1=[charNum charValue];
bool flag1=[boolNum boolValue];
CGPoint point1=[pointVa pointValue];
CGSize size1=[sizeVa sizeValue];
CGRect rect1=[rectVa rectValue];
NSRange range1=[rangeVa rangeValue];
NSEdgeInsets edgeInsets1=[edgeVa edgeInsetsValue];
不可變字元串
字元串分為 :不可變字元串和 可變字元串,其中差別就是,可變字元串的空間是可以改變的,而不可變字元串已被設定了,其空間就是不可改變的了,就算後面一些所謂增加拼接指派操作,也就是改變該不可變字元串的指針而已。
不可變字元串 NSString
可變字元串 NSMutableString
*/
初始化一個字元串對象
NSString *[email protected]"ibokanwisdom";
NSString *string2=[NSString stringWithFormat:@"Jack"];
// NSString *string3=[NSString stringWithFormat:@"%@%@",@"Jack",@"Rick"];
// NSLog(@"%@",string2);
// NSLog(@"%@",string3);
// NSString *string3=[[NSString alloc]initWithFormat:<#(nonnull NSString *), ...#> ];
//NSString *string3=[[NSString alloc]initWithString:@"ibokanwisdom" ];
使用NSString的類方法來建立字元串 +
NSString *string4=[NSString stringWithFormat:@"%@,%d,%f,hi guy",@"Rick",,];
// NSLog(@"%@",string4);
//(lldb)通過斷點裡面的po 輸出的類型 指令列印出來
NSString *[email protected]"Rick";
NSString *[email protected]"666";
NSString *string7=[NSString stringWithFormat:@"%@%@",string5,string6];
NSLog(@"%@",string7);
從本地檔案讀取字元串
NSString *[email protected]"/Users/macpro/Desktop/oc/OC-006-02/OC-006-02/hello.html";
NSError *error;
NSString *string8=[NSString stringWithContentsOfFile:path1 encoding:NSUTF8StringEncoding error:&error];
NSLog(@"string8 =%@,error=%@",string8,error);
從網絡讀取字元串
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
error=nil;
NSString *string9=[NSString stringWithContentsOfURL:url encoding: error:&error];
NSLog(@"%@",string9);
字元串的操作
NSString *[email protected]"你是逗比麼,我都受不了你了";
NSUInteger length=[string10 length];
// NSLog(@"%lu",(unsigned long)length);
NSLog(@"%ld",length);
//字元串的截取
NSString *subString1=[string10 substringToIndex:];
//擷取字元串開頭到字元串的to的位置的字元串内容,不包括to位置的字元串
NSLog(@"subString1=%@",subString1);
NSString *subString2=[string10 substringFromIndex:];
//擷取字元串從from的位置到結尾的字元串,包括from的位置
NSLog(@"%@",subString2);
NSString *subString3=[string10 substringWithRange:NSMakeRange(, )];
NSLog(@"%@",subString3);
NSString *[email protected]"abcdefg";
char c=[string11 characterAtIndex:];//根據字元串的位置index來獲得一個字元,注意字元串的索引從 0 開始。
NSLog(@"%c",c);
字元串的比較,如何判斷兩個字元串是否相等
if(subString2 ==subString3){
//内容和指針都相等的時候,才成立
NSLog(@"subString2和subString3相等");
}else{
NSLog(@"subString2和subString3不相等");
}
淺拷貝和深拷貝
如何讓兩個字元串 指針 和 内容 都相同?
深拷貝和淺拷貝的差別
淺拷貝:對象和拷貝的内容共用一份實體,僅僅是引用的變量名稱不一樣。
深拷貝:原對象和拷貝的對象互相獨立,其中任何一個對象的改動都不會對另一個對象造成影響
NSString *subString4=[NSString stringWithString:subString2];
//NSString *subString4=[NSString stringWithFormat:subString2]; 指針不一樣
if(subString2 ==subString4){
//内容和指針都相等的時候,才成立
NSLog(@"subString2和subString4相等");
}else{
NSLog(@"subString2和subString4不相等");
}
//在實際開發過程中,我們通常通過隻需要比較兩個字元串的内容是否想等
if ([subString2 isEqualToString:subString4]) {
NSLog(@"subString2和subString4相等");
}else{
NSLog(@"subString2和subString4不相等");
}
比較兩個字元串的大小
NSString *[email protected]"hehehehe";
NSString *[email protected]"hahaha";
NSComparisonResult result=[cmpString1compare:cmpString2];
switch (result) {
case NSOrderedAscending:{
NSLog(@"cmpString1 < cmpString2,升序");
break;
}
case NSOrderedSame:{
NSLog(@"cmpString1 = cmpString2");
break;
}
case NSOrderedDescending:{
NSLog(@"cmpString1 > cmpString2,降序");
break;
}
default:
break;
}
根據字元串拿到對應的range
NSRange range=[string10 rangeOfString:@"逗比"];
NSLog(@"%@",[NSValue valueWithRange:range]);
指數出第一個遇到該字元串的位置及該字元串
NSRange range1=[string1 rangeOfString:@"你"];
NSLog(@"%ld,%ld",range1.location,range1.length);
判斷字元串中是否有 xx 字首或 xx字尾
NSString *[email protected]"http://www.baidu.com";
if([string12 hasPrefix:@"http://"]){
NSLog(@"含有此字首");
}else{
NSLog(@"不含有此字首");
判斷是否為 .jpg 和 .png字尾
NSString *[email protected]"xxxxx.jpg";
if ([string13 hasSuffix:@".jpg"] || [string13 hasSuffix:@".png"]) {
NSLog(@"含有此字首");
}else{
NSLog(@"不含有此字尾");
}
字元串的拼接
NSString *[email protected]"www.baidu.com";
NSString *string15=[@"http://"stringByAppendingString:string14];
NSLog(@"%@",string15);
//http://static.bigstockphoto.com/images/homepage/2016_popular_photo_categories.jpg
NSString *string16 [email protected]"http://static.bigstockphoto.com";
NSString *string17 [email protected]"images/homepage/2016_popular_photo_categories.jpg";
NSString *string18=[string16 stringByAppendingFormat:@"/%@",string17];//連接配接兩個字元串, 并且第二個字元串是按一定格式傳進來的
NSString *string19=[string16 stringByAppendingPathComponent:string17];//檔案夾路徑的拼接
NSString *[email protected]"http://static.bigstockphoto.com/images/homepage/2016_popular_photo_categories.jpg";
imagePath = [imagePath lastPathComponent];//取出最後一個反斜杠的内容
NSString *[email protected]"Rick";
theImageName = [theImageName stringByAppendingPathExtension:@"png"];
字元串的其他常用工作
1.字元串的轉換函數
NSString *str[email protected]"111addd33";
int a1=[str intValue];
NSLog(@"%d",a1);
2.字元串的大小寫轉換
NSString *str2= @"aAabb";
NSString *str3= [str2 uppercaseString];//将字元全部改成大寫
NSString *str4=[str3 lowercaseString];//将自負全部改成小寫
NSString *str5=[str4 capitalizedString];//将首個字元改成大寫,其餘的都小寫
NSString *str6=[str2 stringByReplacingOccurrencesOfString:@"bb" withString:@"dd"];
NSString *str7
=[str2 stringByReplacingCharactersInRange:NSMakeRange(,) withString:@"GG"];
NSString *[email protected]"aa-bb-cc-dd-ee";
NSArray *array=[str8 componentsSeparatedByString:@"-"];//以separator為分隔符,将原字元串的内容進行分割,分割得到的結果放到一個數組裡面,作為傳回值;
可變字元串
變字元串的父類是不可變字元串,是以不可變字元串的方法對于可變字元串也是适用的:
NSMutableString *mString=[NSMutableString stringWithString:@"nihao"];
NSMutableString *mString1=[NSMutableString stringWithFormat:@"%@",mString];
NSMutableString *mString2=[NSMutableString stringWithContentsOfFile:@"" encoding: error:nil];
NSMutableString *mString3= [NSMutableString stringWithContentsOfURL:[NSURL URLWithString:@""] encoding:NSUTF8StringEncoding error:nil];
可變字元串獨特的初始化方法
可變字元串獨特的初始化方法,初始化一個空間為100的可變字元串
NSMutableString *mString4= [[NSMutableString alloc]initWithCapacity:];
将c語言的字元串轉換成OC的字元串
[[NSString alloc]initWithCharacters:<#(nonnull const unichar *)#> length:<#(NSUInteger)#>]
可變字元串還可以進行增删改操作,我們可以用一下例子說明一下簡單的語言屏蔽:
NSMutableString *targetString =[NSMutableString stringWithString:@"呵呵,我靠"];
NSRange range=[targetString rangeOfString:@"靠"];
// NSLog(@"%@",[NSValue valueWithRange:range]);
替代
增
//指數出第一個遇到該字元串的位置及該字元串的長度
//在指定位置去一個字元串
[targetString insertString:@"ee" atIndex:];
//在字元串末尾添加一個末尾
[targetString appendString:@"aaa"];
//在字元串的末尾添加多個字元串
[targetString appendFormat:@"%@",@"cc",@"dd"];