最近踩了多個string的坑,嗯嗯!還是要抽時間總結一下的,順便在后面寫幾個自己寫的或者學習別人的算法
1、NSString的創(chuàng)建
//使用字面量創(chuàng)建字符串
NSString *string_0 = @"afeixiaohuozi";
//使用類方法創(chuàng)建字符串
NSString * string_1 = [NSString string];
string_1 = @"afeixiaohuozi";//字符串賦值
//創(chuàng)建一個字符串,并且將內容設置為string
NSString * string_2 = [NSString stringWithString:string_1];
//格式化創(chuàng)建字符串(按照格式輸出)
NSString * string_3 = [NSString stringWithFormat:@"%@",string_1];
NSString * string_4 = [NSString stringWithFormat:@"hello %d %c",5,'A'];
//實例方法初始化
NSString *string_5 = [[NSString alloc] init];
//實例方法指定字符串
NSString *string_6 = [[NSString alloc] initWithString:string_3];
//實例方法創(chuàng)建字符串
NSString *string_7 = [[NSString alloc] initWithFormat:@"%@",string_4 ];
2、NSString的常用方法
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
NSString *string_7 = [NSString stringWithFormat:@"afeixiaohuozi"];
//獲取字符串長度(有效字符長度,不包括'\0')
NSInteger length = [string_7 length];
//同樣可以
NSInteger length = string_7.length;
//檢測字符是否以指定內容開頭
if ([string_7 hasPrefix:@"shan"]) {
NSLog(@"是的");
}
//檢測字符串是否以指定內容結尾
if ([string_7 hasSuffix:@"long"]) {
NSLog(@"是的");
}
//字符串截取
//從哪個索引開始截取到字符串末尾(包含索引位置)
NSString *str0 = [string substringFromIndex:4];
//從字符串開頭截取到哪個索引(不包含索引位置)
NSString *str1 = [string substringToIndex:8];
//截取一定范圍(從下標3開始截取4個字符)
NSRange range = {3,4};
NSString *str2 = [string substringWithRange:range];
//關于NSRange的相關用法
//關于NSRange,請參考另一篇文章:添加鏈接
- (NSRange)rangeOfString:(NSString *)searchString;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
//NSStringCompareOptions相關鏈接
//用于字符串的檢索
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
//不區(qū)分大小寫比較
NSCaseInsensitiveSearch = 1,
//逐字節(jié)比較 區(qū)分大小寫
NSLiteralSearch = 2,
//從字符串末尾開始搜索
NSBackwardsSearch = 4,
//搜索限制范圍的字符串
NSAnchoredSearch = 8,
//按照字符串里的數(shù)字為依據(jù),算出順序。例如 Foo2.txt < Foo7.txt < Foo25.txt
NSNumericSearch = 64,
//忽略 "-" 符號的比較
NSDiacriticInsensitiveSearchNS_ENUM_AVAILABLE(10_5, 2_0) = 128,
//忽略字符串的長度,比較出結果
NSWidthInsensitiveSearchNS_ENUM_AVAILABLE(10_5, 2_0) = 256,
//忽略不區(qū)分大小寫比較的選項,并強制返回 NSOrderedAscending 或者 NSOrderedDescending
NSForcedOrderingSearchNS_ENUM_AVAILABLE(10_5, 2_0) = 512,
//只能應用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比較方法,如果設置此項,可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
NSRegularExpressionSearchNS_ENUM_AVAILABLE(10_7, 3_2) = 1024
};
3、NSString比較
NSString *string_8 = @"afeixiaohozi";
NSString *string_9 = @"hai afeixiaohuozi";
//比較地址
//有一個例外,若是這兩個字符串的內容是相同的,那么,這個 == 就是成立的,因為指針指向同一個地址
if (string_8 == string_9) {
}
//比較內容
if ([string_8 isEqualToString:string_9]) {
NSLog(@"一樣的~~");
}else {
NSLog(@"不一樣~~");
}
if ([string_8 compare:string_9] == NSOrderedSame) {
NSLog(@"相等");
}
else if ([string_8 compare:string_9] == NSOrderedAscending)
{
NSLog(@"升序");
}
else if ([string_8 compare:string_9] == NSOrderedDescending)
{
NSLog(@"降序");
}
//NSCaseInsensitiveSearch 忽略大小寫(@“123”,@“0123”字符串比較)
NSComparisonResult result = [string_8 compare:string_9 options:NSCaseInsensitiveSearch];
if (result == NSOrderedSame) {
NSLog(@"相等");
}else if (result == NSOrderedAscending) {
NSLog(@"升序");
}else if (result == NSOrderedDescending) {
NSLog(@"降序");
}
}
//比較返回值
typedef NS_CLOSED_ENUM(NSInteger, NSComparisonResult) {
NSOrderedAscending = -1L, //升序 :前者大于后者
NSOrderedSame, //相等
NSOrderedDescending //降序 :前者小于后者
};
NSString的compare相關方法還有很多,沒有一一進行使用,
嗯嗯,放在這里吧!萬一啥時候去查詢一下
#pragma mark *** String comparison and equality ***
/* In the compare: methods, the range argument specifies the subrange, rather than the whole, of the receiver to use in the comparison. The range is not applied to the search string. For example, [@"AB" compare:@"ABC" options:0 range:NSMakeRange(0,1)] compares "A" to "ABC", not "A" to "A", and will return NSOrderedAscending. It is an error to specify a range that is outside of the receiver's bounds, and an exception may be raised.
*/
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; // locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice.
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
- (NSComparisonResult)localizedCompare:(NSString *)string;
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
/* localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.
*/
- (NSComparisonResult)localizedStandardCompare:(NSString *)string API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
4、字符串拼接
//字符串拼接
NSString *string_10 = [string_7 stringByAppendingString:string_8];
NSString *string_11 = [NSString stringWithFormat:@"%@%@",string_7,string_8];
NSString *string_12 = [string_7 stringByAppendingFormat:@"-%@",string11];
//將數(shù)字字符串轉換為數(shù)字
NSString *string_13 = @"123";
NSInteger integer = [string13 integerValue];
//字符串所有字符大寫
NSString *string_14 = @"afeixiaohuozi";
NSString *str14 = [string_14 uppercaseString];
//字符串所有字符小寫
NSString *string_15 = @"AFEIXIAOHUOZI";
NSLog(@"%@",[string_15 lowercaseString]);
//首字母大寫
NSLog(@"%@",[string_14 capitalizedString]);
//替換
NSString *string_16 = @"文藝青年";
string_16 = [string_16 stringByReplacingOccurrencesOfString:@"文藝" withString:@"偽文藝"];
//刪除原字符串中的所有指定字符,變?yōu)榭?NSString * string_18 = [string_16 stringByReplacingOccurrencesOfString:@"文" withString:@""];
//從下標0開始替換2長度的字符
NSString *string_17 = [string_16 stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:@"真的是"];
NSRange rang = [string_16 rangeOfString:@"文藝"];
string_17 = [string_16 stringByReplacingCharactersInRange:rang withString:@"哈哈哈"];
//去掉兩端空格
string_18 = [string_7 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//C語言字符串轉化成OC字符串
NSString *str_20 = [NSString stringWithCString:"afeixiaohozi" encoding:NSUTF8StringEncoding];
//OC語言字符串轉化成C字符串
const char *cStr = [string_8 cStringUsingEncoding:NSUTF8StringEncoding];
5、字符串拼接時候的坑
在修改一個bug的時候,平時用NSString字符串拼接總是失?。ㄟ€是自己太粗心了)
NSString 的拼接方法是有返回值的,只有在返回值里面才是拼接好的字符串
- (NSString *)stringByAppendingString:(NSString *)aString;
- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//NSString 的拼接方法是有返回值的,只有在返回值里面才是拼接好的字符串
NSString *string_1 = nil;
NSString *string_2 = @"Afeixiaohiozi";
[string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1); //string_1 = (null)
//因為sring_1為空 結果返回值依舊是 nil
string_1 = [string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1);//string_1 = (null)
//so ,至少應該下面這樣
NSString *string_1 = [NSString string] ;
NSString *string_2 = @"Afeixiaohiozi";
string_1 = [string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1);//string_1 = Afeixiaohiozi
//或者像這樣
NSString *string_1 = @"I Am " ;
NSString *string_2 = @"Afeixiaohiozi";
string_1 = [string_1 stringByAppendingString:string_2];
NSLog(@"string_1 = %@",string_1); //string_1 = I Am Afeixiaohiozi
//當然,也有沒有返回值的拼接
//NSMutableString相關方法,也應該好好總結一下了
NSMutableString *nameStr = [NSMutableString string]
[nameStr appendString:string_2];
NSLog(@"nameStr = %@",nameStr);//nameStr = Afeixiaohiozi
//如果
NSMutableString *nameStr;
[nameStr appendString:string_2];
NSLog(@"nameStr = %@",nameStr); //nameStr = (null)
/*
不論是NSString 或者 NSMutableString 存儲拼接后的字符串都是需要先申請空間的
*/
6、獲取NSString中所有匹配子字符串的NSRange的array
NSString *string1=@"abcdefabcdefabcdefabcdefbcd";
NSString *string2=@"bcd";
NSArray *array=[string1 componentsSeparatedByString:string2];
NSMutableArray *arrayOfLocation=[NSMutableArray array];
int d=0;
for (int i = 0; i < array.count - 1; i++) {
NSString *string = array[i];
NSNumber *number = [NSNumber numberWithInt:d += string.length];
d += string2.length;
[arrayOfLocation addObject:number];
}
NSLog(@"%@",arrayOfLocation);
7、高亮規(guī)定字符串
//搜索匹配算法
//高亮<em></em>中間的字符串
//NSString *aString = @"I am a <em>string</em>, not a a<em>string</em>, just a <em>string</em>";
- (NSMutableAttributedString *)newSetSearchResultStringColor:(NSString *)importString {
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:importString];
NSString *subString_1 = @"<em>";
NSString *subString_2 = @"</em>";
//獲取subString_1的下標位置
NSArray *subString_1_array=[importString componentsSeparatedByString:subString_1];
NSMutableArray *arrayOfLocation1 = [NSMutableArray array];
int d = 0;
for (int i = 0; i < subString_1_array.count - 1; i++) {
NSString *string = subString_1_array[i];
NSNumber *number = [NSNumber numberWithInt:d += string.length];
d += subString_1.length;
[arrayOfLocation1 addObject:number];
}
//獲取subString_2的下標位置
NSArray *subString_2_array=[importString componentsSeparatedByString:subString_2];
NSMutableArray *arrayOfLocation2 = [NSMutableArray array];
d = 0;
for (int i = 0; i < subString_2_array.count - 1; i++) {
NSString *string = subString_2_array[i];
NSNumber *number = [NSNumber numberWithInt:d += string.length];
d += subString_2.length;
[arrayOfLocation2 addObject:number];
}
//高亮中間string 刪除標記string
NSInteger i = arrayOfLocation1.count - 1;
NSInteger j = arrayOfLocation2.count - 1;
for ( ;i >= 0 && j >= 0; i-- ,j--) {
NSInteger location_1 = [arrayOfLocation1[i] integerValue];
NSInteger location_2 = [arrayOfLocation2[j] integerValue];
//高亮的起始位置應該是在標記字符串后面
NSRange range = {location_1 + 4 , location_2 - location_1 - 4};
[resultString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(range.location,range.length)];
NSRange locationRange_1 = {location_1,4};
NSRange locationRange_2 = {location_2,5};
[resultString deleteCharactersInRange:locationRange_2];
[resultString deleteCharactersInRange:locationRange_1];
}
return resultString;
}
8、高亮所有匹配的字符
//NSString *inputString = @" a of American";
//NSString *showString = @"of I am office a of and American";
//inputString是輸入的字符,要讓showString中所有與inputString想匹配的單詞高亮
- (NSMutableAttributedString *)showHeightLightLabel:(NSString*)inputString showLabel:(NSString*)showlabel
{
NSString *newInputLabel = [inputString lowercaseString];
NSString *newShowLabel = [showlabel lowercaseString];
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:showlabel];
NSCharacterSet *chartSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *chartStringArray = [newInputLabel componentsSeparatedByCharactersInSet:chartSet];
NSLog(@"%@",chartStringArray);
for (NSString* chart in chartStringArray) {
NSArray *showLabelArray = [newShowLabel componentsSeparatedByString:chart];
NSLog(@"%@",showLabelArray);
NSInteger location = 0;
for (NSString *showLabel in showLabelArray) {
location += showLabel.length;
if (location >= resultString.length) {
continue;
}
NSRange chartRange = NSMakeRange(location, chart.length);
[resultString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(chartRange.location,chartRange.length)];
location += chart.length;
}
}
return resultString;
}
//NSString *inputString = @" a of American";
//NSString *showString = @"of I am office a of and American";
//inputString是輸入的字符,要讓showString中所有與inputString想匹配的單詞高亮
//需求中要求忽略某些文本開頭的內容,所以引入ignoreString
//此算法可以兼容上面的高亮算法
- (NSMutableAttributedString *)showHeightLightLabel:(NSString*)inputString showLabel:(NSString*)showlabel withIgnoreString:(NSString *)ignoreString
{
NSString *newInputLabel = [inputString lowercaseString];
NSString *newShowLabel = [showlabel lowercaseString];
NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithString:showlabel];
NSCharacterSet *chartSet = [NSCharacterSet whitespaceCharacterSet];
NSMutableArray *chartStringArray = [NSMutableArray arrayWithArray:[newInputLabel componentsSeparatedByCharactersInSet:chartSet]];
[chartStringArray removeObject:@"/"];
NSLog(@"%@",chartStringArray);
for (NSString* chart in chartStringArray) {
NSArray *showLabelArray = [newShowLabel componentsSeparatedByString:chart];
NSLog(@"%@",showLabelArray);
NSInteger location = 0;
for (NSString *showLabel in showLabelArray) {
location += showLabel.length;
if (location >= resultString.length || location < ignoreString.length) {
location += chart.length;
continue;
}
NSRange chartRange = NSMakeRange(location, chart.length);
[resultString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(chartRange.location,chartRange.length)];
location += chart.length;
}
}
return resultString;
}
注:本文也參考了一些文章,在此表示感謝