本文对OC的NSString类的方法属性做了一个全面的测试,完全是基础,没兴趣的就不用看这个浪费时间了:
//
// string.m
// GVRegularExpressionDemo
//
// Created by gavin on 15/8/29.
// Copyright (c) 2015年 GV. All rights reserved.
//
#import "string.h"
#import <Foundation/NSPropertyList.h>
@implementation string
-(void)stringTest{
#pragma mark NSString
NSString *str = [NSString stringWithFormat:@"NSString Test..."];
NSLog(@"%@",str);
NSStringEncoding encode;
///////////////////// Creating and Initializing Strings /////////////////////
const char* chs = "gavinZhang";
unichar unichs[] = {'g','a','v','i','n','Z','h','a','n','g','1'};
// + string //empty string.
NSLog(@"%d",(int)[[NSString string] length]);
// -init
NSLog(@"%d",(int)[[[NSString alloc] init] length]);
// - initWithBytes:length:encoding:
str = [[NSString alloc] initWithBytes:chs length:5 encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
// - initWithBytesNoCopy:length:encoding:freeWhenDone:
NSData *aData = [NSData dataWithBytes:chs length:strlen(chs)];
Byte *byte = (Byte*)[aData bytes];
Byte *buffer = malloc(strlen(chs));
memccpy(buffer, byte, 0, strlen(chs));
str = [[NSString alloc] initWithBytesNoCopy:(void *)byte length:strlen(chs) encoding:NSUTF8StringEncoding freeWhenDone:NO];
NSLog(@"str = %@", str);
str = [[NSString alloc] initWithBytesNoCopy:(void *)buffer length:strlen(chs)-1 encoding:NSUTF8StringEncoding freeWhenDone:YES];
NSLog(@"str = %@", str);
//此行会产生crash, 因为上一次指定freeWhenDone为yes后, buffer已经被释放;
//str = [[NSString alloc] initWithBytesNoCopy:(void *)buffer length:strlen(chs)-1 encoding:NSUTF8StringEncoding freeWhenDone:YES];
//NSLog(@"str = %@", str);
// - initWithCharacters:length:
str = [[NSString alloc] initWithCharacters:unichs length:3];
NSLog(@"str = %@", str);
// - initWithCharactersNoCopy:length:freeWhenDone:
str = [[NSString alloc] initWithCharactersNoCopy:unichs length:sizeof(unichs)/sizeof(unichs[0]) freeWhenDone:NO];
NSLog(@"str = %@", str);
// - initWithString:
NSLog(@"%p",str);
str = [[NSString alloc] initWithString:str];
NSLog(@"%p",str);
NSLog(@"%@", str);
// - initWithCString:encoding:
str = [[NSString alloc] initWithCString:chs encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
// - initWithUTF8String:
str = [[NSString alloc] initWithUTF8String:chs];
NSLog(@"%@", str);
// - initWithFormat:arguments:
str = [self vaListTest:@"gavin",@" Zhang",@" va_list",@" test"];
NSLog(@"str = %@",str);
// - initWithFormat:locale:
str = [[NSString alloc] initWithFormat:@"%@" locale:[NSLocale currentLocale], @"gavinZhang_NSLocale"];
NSLog(@"str = %@",str);
// - initWithFormat:locale:arguments:
str = [self vaListTest:@"gavin",@" Zhang",@" va_list",@" test"];
NSLog(@"str = %@",str);
// - initWithData:encoding:
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
// + stringWithFormat: // - initWithFormat:
str = [[NSString alloc] initWithFormat:@"gavin%@",@"Zhang" ];
NSLog(@"str = %@",str);
str = [NSString stringWithFormat:@"gavin%@",@"Zhang2"];
NSLog(@"str = %@",str);
// + localizedStringWithFormat: //This method is equivalent to using initWithFormat:locale: and passing the current locale as the locale argument.
str = [NSString localizedStringWithFormat:@"%@",@"stringTest"];
NSLog(@"str = %@",str);
// + stringWithCharacters:length:
str = [NSString stringWithCharacters:unichs length:sizeof(unichs)/sizeof(unichs[0])];
NSLog(@"str = %@",str);
// + stringWithString:
NSLog(@"str.address = %p",str);
str = [NSString stringWithString:str];
NSLog(@"str.address = %p",str);
//+ stringWithCString:encoding:
str = [NSString stringWithCString:chs encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
// + stringWithUTF8String:
str = [NSString stringWithUTF8String:chs];
NSLog(@"str = %@",str);
////////////////////////// Creating and Initializing a String from a File //////////////////////////
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"test.txt"];
NSLog(@"path = %@",path);
[str writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil];
// + stringWithContentsOfFile:encoding:error:
NSError *error = nil;
str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSLog(@"str = %@, error = %@",str,error);
}else{
NSLog(@"error = %@", error);
}
// - initWithContentsOfFile:encoding:error:
//如果你想在缺少编码信息的情况下,猜出编码,可以使用stringWithContentsOfFile:usedEncoding:error:或者 initWithContentsOfFile:usedEncoding:error: 方法
str = [[NSString alloc] initWithContentsOfFile:path usedEncoding:&encode error:&error];
NSLog(@"str = %@, error = %@, encode = %d",str,error,(int)encode);
// + stringWithContentsOfFile:usedEncoding:error:
str = [NSString stringWithContentsOfFile:path usedEncoding:&encode error:nil];
NSLog(@"str = %@, error = %@, encode = %d",str,error,(int)encode);
////////////////////////// Creating and Initializing a String from an URL //////////////////////////
// + stringWithContentsOfURL:encoding:error:
//远程
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str.lentgh = %ld, error = %@, encode = %d",str.length,error,(int)encode);
//本地
url = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",path]];
str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@, error = %@, path = %@, url = %@" ,str, error, path, url);
// - initWithContentsOfURL:encoding:error:
str = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@, error = %@, path = %@, url = %@" ,str, error, path, url);
// + stringWithContentsOfURL:usedEncoding:error:
str = [NSString stringWithContentsOfURL:url usedEncoding:&encode error:nil];
NSLog(@"str = %@, error = %@, path = %@, usedEncoding = %d, url = %@" ,str, error, path, (int)encode, url);
// - initWithContentsOfURL:usedEncoding:error:
str = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&encode error:nil];
NSLog(@"str = %@, error = %@, path = %@, usedEncoding = %d, url = %@" ,str, error, path, (int)encode, url);
////////////////////////// Writing to a File or URL //////////////////////////
// - writeToFile:atomically:encoding:error:
[str writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"error = %@",error);
}else{
str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str1 = %@, error = %@",str, error);
}
// - writeToURL:atomically:encoding:error:
[str writeToURL:url atomically:NO encoding:NSUTF8StringEncoding error:&error];
if (!error) {
NSLog(@"str2 = %@, error = %@",str, error);
}
////////////////////////// Getting a String’s Length //////////////////////////
//length Property
NSLog(@"str.length = %d", (int)str.length);
// - lengthOfBytesUsingEncoding: //当用enc对字符串进行编码时,用于存储数组所需要的字节数。
str = @"张先生";
int length = (int)str.length;
int unicodeLen = (int)[str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding];
int utf8Len = (int)[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
int utf16Len = (int)[str lengthOfBytesUsingEncoding:NSUTF16StringEncoding];
int utf32Len = (int)[str lengthOfBytesUsingEncoding:NSUTF32StringEncoding];
NSLog(@"length = %d, utf16Len = %d = unicodeLen = %d, utf8Len = %d, utf32Len = %d", length, utf16Len, unicodeLen, utf8Len, utf32Len);
// - maximumLengthOfBytesUsingEncoding: //返回当用enc对字符串进行编码存储时,所需要的最大字节数。
str = @"a哈哈哈";
NSLog(@"\n\nlength = %ld", str.length);
NSLog(@"utf16Len = %d", (int)[str maximumLengthOfBytesUsingEncoding:NSUTF16StringEncoding]);
NSLog(@"unicodeLen = %d", (int)[str maximumLengthOfBytesUsingEncoding:NSUnicodeStringEncoding]);
NSLog(@"utf8Len = %d", (int)[str maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
NSLog(@"utf32Len = %d", (int)[str maximumLengthOfBytesUsingEncoding:NSUTF32StringEncoding]);
////////////////////////// Getting Characters and Bytes //////////////////////////
// - characterAtIndex:
str = @"gavin";
NSLog(@"\n\n [str characterAtIndex:0]: %c",[str characterAtIndex:0]);
// - getCharacters:range:
str = @"gavinZhang";
unichar *buffer2 = malloc(10);
[str getCharacters:buffer2 range:NSMakeRange(0, 10)];
NSLog(@"[str getCharacters:buffer2 range:NSMakeRange(0, 10)] : %S", (const unichar*)buffer2);
free(buffer2);
// - getBytes:maxLength:usedLength:encoding:options:range:remainingRange:
NSData *strData = [str dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES];
NSUInteger dataLength = [strData length];
Byte *byteData = (Byte*)malloc( dataLength );
memcpy( byteData, [strData bytes], dataLength );
NSUInteger numberOfBytes = [str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding];
void *buffer3 = malloc(numberOfBytes);
bzero(buffer3, numberOfBytes);
NSUInteger usedLength = 0;
NSRange range = NSMakeRange(0, [str length]);
BOOL result = [str getBytes:buffer3 maxLength:numberOfBytes usedLength:&usedLength encoding:NSUnicodeStringEncoding options:0 range:range remainingRange:NULL];
NSLog(@"buffer3 = %S, result = %d, usedLength = %ld",(const unichar*)buffer3, result, usedLength);
str = [NSString stringWithFormat:@"%S",(const unichar*)buffer3];
NSLog(@"buffer3 to nsstring -> %@", str);
free(buffer3);
////////////////////////// Getting C Strings //////////////////////////
// - cStringUsingEncoding:
const char *chs2 = [str cStringUsingEncoding:NSASCIIStringEncoding];
NSLog(@"chs2%%s = %s, chs2%%S = %S", chs2, (const unichar*)chs2);
chs2 = [str cStringUsingEncoding:NSUnicodeStringEncoding];
NSLog(@"chs2%%s = %s, chs2%%S = %S", chs2, (const unichar*)chs2);
// - getCString:maxLength:encoding:
str = @"gavinZhang";
char buffer4[512];
result = [str getCString:buffer4 maxLength:512 encoding:NSUnicodeStringEncoding];
if (result) {
NSLog(@"buffer4 = %S",(const unichar*)buffer4);
}
// UTF8String Property
const char *str3 = [str UTF8String];
NSLog(@"str3 = %s",str3);
////////////////////////// Combining Strings //////////////////////////
// - stringByAppendingFormat:
str = [str stringByAppendingFormat:@" hello%@",@"!"];
NSLog(@"str = %@", str);
// - stringByAppendingString:
str = [str stringByAppendingString:@"!"];
NSLog(@"str = %@", str);
// - stringByPaddingToLength:withString:startingAtIndex:
str = [str stringByPaddingToLength:str.length withString:@"_instert_" startingAtIndex:2];
NSLog(@"str = %@", str);
////////////////////////// Dividing Strings //////////////////////////
// - componentsSeparatedByString:
str = @"Gavin Zhang hello";
NSArray *arr = [str componentsSeparatedByString:@" "];
NSLog(@"arr = %@", arr);
// - componentsSeparatedByCharactersInSet:
arr = [str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"a "]];
NSLog(@"arr = %@", arr);
// - stringByTrimmingCharactersInSet: //在字符串的首或尾、删除字符集合组成的字符串
NSString *str2 = [str stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"lohe"]];
NSLog(@"str2 = %@", str2); //结果: str2 = Gavin Zhang
// - substringFromIndex:
str2 = [str substringFromIndex:6];
NSLog(@"str2 = %@", str2);
// - substringWithRange:
str2 = [str substringWithRange:NSMakeRange(0, 5)];
NSLog(@"str2 = %@", str2);
// - substringToIndex:
str2 = [str substringToIndex:8];
NSLog(@"str2 = %@", str2);
////////////////////////// Finding Characters and Substrings //////////////////////////
// - rangeOfCharacterFromSet: //从头向尾查找, 直到找到第一个字符为至.
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"In"];
range = [str rangeOfCharacterFromSet:set];
NSLog(@"range = %@, str = %@",NSStringFromRange(range),str);
// - rangeOfCharacterFromSet:options:
// options:(NSStringCompareOptions)
// enum{
// NSCaseInsensitiveSearch = 1,//不区分大小写比较
// NSLiteralSearch = 2,//区分大小写比较
// NSBackwardsSearch = 4,//从字符串末尾开始搜索
// NSAnchoredSearch = 8,//搜索限制范围的字符串
// NSNumbericSearch = 64//按照字符串里的数字为依据,算出顺序。例如 Foo2.txt < Foo7.txt < Foo25.txt
// //以下定义高于 mac os 10.5 或者高于 iphone 2.0 可用
// NSDiacriticInsensitiveSearch = 128,//忽略 "-" 符号的比较
// NSWidthInsensitiveSearch = 256,//忽略字符串的长度,比较出结果
// NSForcedOrderingSearch = 512//忽略不区分大小写比较的选项,并强制返回 NSOrderedAscending 或者 NSOrderedDescending
// //以下定义高于 iphone 3.2 可用
// NSRegularExpressionSearch = 1024//只能应用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比较方法,如果设置此项,可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
// }
set = [NSCharacterSet characterSetWithCharactersInString:@"In"];
range = [str rangeOfCharacterFromSet:set options:NSBackwardsSearch];
NSLog(@"range = %@, str = %@",NSStringFromRange(range),str);
// - rangeOfCharacterFromSet:options:range:
range = [str rangeOfCharacterFromSet:set options:NSBackwardsSearch range:NSMakeRange(0, str.length)];
NSLog(@"range = %@, str = %@",NSStringFromRange(range),str);
// - rangeOfString:
range = [str rangeOfString:@"Zhang"];
NSLog(@"range = %@, str = %@",NSStringFromRange(range),str);
// - rangeOfString:options:
range = [str rangeOfString:@"in" options:0 range:NSMakeRange(0, str.length) locale:[NSLocale currentLocale]];
NSLog(@"range = %@, str = %@",NSStringFromRange(range),str);
// - enumerateLinesUsingBlock:
str = @"Gavin \n Zhang \n Hello!";
[str enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
NSLog(@"line = %@, BOOL = %d",line, (int)stop);
if ([line rangeOfString:@"zhang" options:NSCaseInsensitiveSearch].location != NSNotFound) {
*stop = YES; //return;
}
}];
// - enumerateSubstringsInRange:options:usingBlock:
//typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) {
// // Pass in one of the "By" options:
// NSStringEnumerationByLines = 0, // Equivalent to lineRangeForRange:
// NSStringEnumerationByParagraphs = 1, // Equivalent to paragraphRangeForRange:
// NSStringEnumerationByComposedCharacterSequences = 2, // Equivalent to rangeOfComposedCharacterSequencesForRange:
// NSStringEnumerationByWords = 3,
// NSStringEnumerationBySentences = 4,
// // ...and combine any of the desired additional options:
// NSStringEnumerationReverse = 1UL << 8,
// NSStringEnumerationSubstringNotRequired = 1UL << 9,
// NSStringEnumerationLocalized = 1UL << 10 // User's default locale
//};
[str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationByLines usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
NSLog(@"substring = %@, substringRange = %@, enclosingRange = %@",
substring, NSStringFromRange(substringRange), NSStringFromRange(enclosingRange));
}];
////////////////////////// Replacing Substrings //////////////////////////
// - stringByReplacingOccurrencesOfString:withString:options:range:
str = @"Gavin Zhang";
str = [str stringByReplacingOccurrencesOfString:@"zhang" withString:@"Li" options:NSCaseInsensitiveSearch range:NSMakeRange(0, str.length)];
NSLog(@"str = %@", str);
// - stringByReplacingCharactersInRange:withString:
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, str.length) withString:@"Ta"];
NSLog(@"str = %@", str);
////////////////////////// Determining Line and Paragraph Ranges //////////////////////////
// - getLineStart:end:contentsEnd:forRange: //PS: OC 里用这种方式返回多个值。
str = @"Gavin \n Zhang \n Hello!";
NSUInteger s, e, ce;
[str getLineStart:&s end:&e contentsEnd:&ce forRange:NSMakeRange(0, 1)];
NSLog(@"str = \n%@, s = %ld, e = %ld, ce = %ld, str.length = %ld", str, s, e, ce, str.length);
// - lineRangeForRange:
range = [str lineRangeForRange:NSMakeRange(0, 1)];
NSLog(@"range = %@", NSStringFromRange(range));
// - getParagraphStart:end:contentsEnd:forRange:
[str getParagraphStart:&s end:&e contentsEnd:&ce forRange:NSMakeRange(0, 1)];
NSLog(@"str = \n%@, s = %ld, e = %ld, ce = %ld, str.length = %ld", str, s, e, ce, str.length);
// - paragraphRangeForRange:
range = [str paragraphRangeForRange:NSMakeRange(0, 1)];
NSLog(@"range = %@", NSStringFromRange(range));
////////////////////////// Determining Composed Character Sequences(测试了很久不知道实际用途????) //////////////////////////
//- rangeOfComposedCharacterSequenceAtIndex:
range = [str rangeOfComposedCharacterSequenceAtIndex:8];
NSLog(@"range = %@", NSStringFromRange(range));
//- rangeOfComposedCharacterSequencesForRange:
range = [str rangeOfComposedCharacterSequencesForRange:NSMakeRange(8, 5)];
NSLog(@"range = %@", NSStringFromRange(range));
str = @"THUMB大S UP SIGN";
//str = @"今天天气(qi)很好";
NSLog(@"str.length = %ld", str.length);
for (int i=0; i<str.length; ++i) {
unichar ch = [str characterAtIndex:i];
NSLog(@"ch = %C, i = %d\n", ch, i);
}
printf("\n");
NSRange r;
for(int i=0; i<str.length; i+=r.length){
r = [str rangeOfComposedCharacterSequenceAtIndex:i];
NSString *s = [str substringWithRange:r];
NSLog(@"i = %d, s = %@", i, s);
}
////////////////////////// Converting String Contents Into a Property List //////////////////////////
NSString *str4 =
@"<dict>"
@"<key>CFBundleDevelopmentRegion</key>"
@"<string>en</string>"
@"<key>CFBundleExecutable</key>"
@"<string>$(EXECUTABLE_NAME)</string>"
@"<key>CFBundleIdentifier</key>"
@"<string>com.$(PRODUCT_NAME:rfc1034identifier)</string>"
@"<key>CFBundleInfoDictionaryVersion</key>"
@"<string>6.0</string>"
@"<key>CFBundleName</key>"
@"<string>$(PRODUCT_NAME)</string>"
@"<key>CFBundlePackageType</key>"
@"<string>APPL</string>"
@"<key>CFBundleShortVersionString</key>"
@"<string>1.0</string>"
@"<key>CFBundleSignature</key>"
@"<string>????</string>"
@"<key>CFBundleVersion</key>"
@"<string>1</string>"
@"<key>LSRequiresIPhoneOS</key>"
@"<true/>"
@"<key>UILaunchStoryboardName</key>"
@"<string>LaunchScreen</string>"
@"<key>UIMainStoryboardFile</key>"
@"<string>Main</string>"
@"<key>UIRequiredDeviceCapabilities</key>"
@"<array>"
@"<string>armv7</string>"
@"</array>"
@"<key>UISupportedInterfaceOrientations</key>"
@"<array>"
@"<string>UIInterfaceOrientationPortrait</string>"
@"<string>UIInterfaceOrientationLandscapeLeft</string>"
@"<string>UIInterfaceOrientationLandscapeRight</string>"
@"</array>"
@"</dict>";
NSLog(@"str4 = %@",str4);
// - propertyList //返回多种类型
id pl = [str4 propertyList];
NSLog(@"[str propertyList] = %@", pl);
// - propertyListFromStringsFileFormat //仅字典类型
pl = [str4 propertyListFromStringsFileFormat];
NSLog(@"[str propertyListFromStringsFileFormat] = %@", pl);
str4 =
@"/* Question in confirmation panel for quitting. */"
@"\"Confirm Quit\" = \"Are you sure you want to quit?\";"
@""
@"/* Message when user tries to close unsaved document */"
@"\"Close or Save\" = \"Save changes before closing?\";"
@""
@"/* Word for Cancel */"
@"\"Cancel\";";
NSLog(@"str4 = %@", str4);
pl = [str4 propertyList];
NSLog(@"[str propertyList] = %@", pl);
pl = [str4 propertyListFromStringsFileFormat];
NSLog(@"[str propertyListFromStringsFileFormat] = %@", pl);
////////////////////////// Identifying and Comparing Strings //////////////////////////
//- caseInsensitiveCompare:
str = @"GavinZhang";
NSComparisonResult cmpResult = [str caseInsensitiveCompare:@"gavinzhang"];
NSLog(@"cmpResult = %ld", cmpResult);
//- localizedCaseInsensitiveCompare: //应用场景??????
cmpResult = [str localizedCaseInsensitiveCompare:@"gavinzhang"];
NSLog(@"cmpResult = %ld", cmpResult);
//- compare:
NSLog(@"compare: %ld", [str compare:@"f"]);
NSLog(@"compare: %ld", [str compare:@"GavinZhang"]);
NSLog(@"compare: %ld", [str compare:@"h"]);
//- localizedCompare:
NSLog(@"localizedCompare: %ld", [str localizedCompare:@"f"]);
NSLog(@"localizedCompare: %ld", [str localizedCompare:@"GavinZhang"]);
NSLog(@"localizedCompare: %ld", [str localizedCompare:@"h"]);
//- compare:options:
//- compare:options:range:
//- compare:options:range:locale:
cmpResult = [str compare:@"gavinzhang" options:NSCaseInsensitiveSearch range:NSMakeRange(0, str.length) locale:[NSLocale currentLocale]];
NSLog(@"cmpResult = %ld", cmpResult);
//- localizedStandardCompare: //尽量用于文件名或序列表等, 使用当前的语言环境.
cmpResult = [str localizedStandardCompare:@"gavinzhang"];
NSLog(@"cmpResult = %ld", cmpResult);
//- hasPrefix:
//- hasSuffix:
NSLog(@"str: %@, hasPrefix: %d, hasSuffix: %d", str, [str hasPrefix:@"gavin"], [str hasSuffix:@"zhang"]); //看结果是不区分大小写的.
//- isEqualToString:
NSLog(@"isEqualToString: %@", [str isEqualToString:@"Gavin"] ? @"YES":@"NO");
//hash Property
NSLog(@"hash Property: %ld", [str hash]);
////////////////////////// Folding Strings //////////////////////////
// - stringByFoldingWithOptions:locale: //Folding Strings 折叠字符串, 暂未接触到.
str4 = [str stringByFoldingWithOptions:NSLiteralSearch locale:[NSLocale currentLocale]];
NSLog(@"str4 = %@", str4);
////////////////////////// Getting a Shared Prefix //////////////////////////
// - commonPrefixWithString:options: //包含前缀
str4 = [str commonPrefixWithString:@"g" options:NSCaseInsensitiveSearch];
NSLog(@"str4 = %@", str4); //结果g
////////////////////////// Changing Case //////////////////////////
//capitalizedString Property
//- capitalizedStringWithLocale:
str = @"gavin Zhang";
NSLog(@"capitalizedString: %@, %@",str.capitalizedString, [str capitalizedStringWithLocale:[NSLocale currentLocale]]); //Gavin Zhang
//lowercaseString Property
//- lowercaseStringWithLocale:
NSLog(@"lowercaseString: %@, %@",str.lowercaseString, [str lowercaseStringWithLocale:[NSLocale currentLocale]]);
//uppercaseString Property
//- uppercaseStringWithLocale:
NSLog(@"uppercaseString: %@, %@",str.uppercaseString, [str uppercaseStringWithLocale:[NSLocale currentLocale]]);
////////////////////////// Getting Strings with Mapping //////////////////////////
//decomposedStringWithCanonicalMapping Property //Unicode Normalization Form D
//decomposedStringWithCompatibilityMapping Property //Unicode Normalization Form KD
//precomposedStringWithCanonicalMapping Property //Unicode Normalization Form C
//precomposedStringWithCompatibilityMapping Property //Unicode Normalization Form KC
NSLog(@"decomposedStringWithCanonicalMapping: %@", [str decomposedStringWithCanonicalMapping]);
NSLog(@"decomposedStringWithCompatibilityMapping: %@", [str decomposedStringWithCompatibilityMapping]);
NSLog(@"precomposedStringWithCanonicalMapping: %@", [str precomposedStringWithCanonicalMapping]);
NSLog(@"precomposedStringWithCompatibilityMapping: %@", [str precomposedStringWithCompatibilityMapping]);
////////////////////////// Getting Numeric Values //////////////////////////
//doubleValue Property
//floatValue Property
//intValue Property
//integerValue Property
//longLongValue Property
//boolValue Property
double strDouble = [@"a1" doubleValue];
float strFloat = [@"1a" floatValue];
int strInt = [@"1" intValue];
long strLong = [@"1" longLongValue];
BOOL strBool = [@"2" boolValue];
NSLog(@"strDouble = %lf, strFloat = %f, strInt = %d, strLong = %ld, strBool = %d",strDouble, strFloat, strInt, strLong, strBool);
////////////////////////// Working with Encodings //////////////////////////
str = @"GavinZhang";
//+ availableStringEncodings
const NSStringEncoding *cs = [NSString availableStringEncodings];
NSLog(@"availableStringEncodings: %ld", *cs); //NSMacOSRomanStringEncoding
//+ defaultCStringEncoding //很少用.
NSStringEncoding senc = [NSString defaultCStringEncoding];
NSLog(@"defaultCStringEncoding: %ld", senc);
//+ localizedNameOfStringEncoding:
NSLog(@"localizedNameOfStringEncoding: %@", [NSString localizedNameOfStringEncoding:NSUnicodeStringEncoding]); //Unicode (UTF-16)
//- canBeConvertedToEncoding:
str = @"张先生";
NSLog(@"canBeConvertedToEncoding: %@", [str canBeConvertedToEncoding:NSASCIIStringEncoding] ? @"YES":@"NO");
str = @"GavinZhang";
NSLog(@"canBeConvertedToEncoding: %@", [str canBeConvertedToEncoding:NSASCIIStringEncoding] ? @"YES":@"NO");
//- dataUsingEncoding: //无损转换
//- dataUsingEncoding:allowLossyConversion: //可以删除可修改
str = @"张先生";
strData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(@"strData = %@, strData.length = %ld", strData, strData.length);
//description Property //This NSString object. (read-only)
//fastestEncoding Property //最快编码
//smallestEncoding Property //最小编码
NSLog(@"str.description = %@", str.description);
NSLog(@"str.fastestEncoding = %ld", str.fastestEncoding);
NSLog(@"str.smallestEncoding = %ld", str.smallestEncoding);
strData = [str dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES];
str4 = [[NSString alloc] initWithData:strData encoding:NSUnicodeStringEncoding];
NSLog(@"str4 = %@", str4);
////////////////////////// Working with Paths //////////////////////////
//+ pathWithComponents:
//pathComponents Property
arr = @[@"a",@"//b",@"c",@"d"];
str = [NSString pathWithComponents:arr];
NSLog(@"str = %@", str); //print: a/b/c/d
arr = str.pathComponents;
NSLog(@"arr = %@", arr);
//- completePathIntoString:caseSensitive:matchesIntoArray:filterTypes: //查找磁盘上的文件, 可指定查找类型
//create file
NSString *f1 = [NSHomeDirectory() stringByAppendingPathComponent:@"a.txt"];
NSString *f2 = [NSHomeDirectory() stringByAppendingPathComponent:@"aa.txt"];
[str writeToFile:f1 atomically:NO encoding:NSUTF8StringEncoding error:nil];
[str writeToFile:f2 atomically:NO encoding:NSUTF8StringEncoding error:nil];
//find file
NSString *partialPath = [NSHomeDirectory() stringByAppendingPathComponent:@"a"];
NSArray *outputArray;
NSArray *filterTypes = @[@"txt", @"rtf"];
NSString *outputName;
NSUInteger textMatches = [partialPath completePathIntoString:&outputName
caseSensitive:NO
matchesIntoArray:&outputArray
filterTypes:filterTypes];
NSLog(@"outputArray = %@, outputName = %@, textMatches = %ld",outputArray, outputName, textMatches);
//fileSystemRepresentation Property //CStyle string
str = outputArray[0];
NSLog(@"str.fileSystemRepresentation = %s", str.fileSystemRepresentation);
//- getFileSystemRepresentation:maxLength:
char fileCStyle[512];
BOOL boolV = [str getFileSystemRepresentation:fileCStyle maxLength:19]; //maxLength <= 实际字符串长度时 可能会失败.
NSLog(@"str.length = %ld, str.fileSystemRepresentation = %s, boolV = %d", str.length, fileCStyle, boolV);
//absolutePath Property
NSLog(@"str.absolutePath = %@", str.absolutePath ? @"YES":@"NO");
//lastPathComponent Property
NSLog(@"str.lastPathComponent = %@", str.lastPathComponent);
//pathExtension Property
NSLog(@"str.pathExtension = %@", str.pathExtension);
//stringByAbbreviatingWithTildeInPath Property
NSLog(@"str.stringByAbbreviatingWithTildeInPath = %@", str.stringByAbbreviatingWithTildeInPath); // ~/a.txt
//- stringByAppendingPathComponent:
//- stringByAppendingPathExtension:
str = [str stringByAppendingPathComponent:@"a.txt"];
str = [str stringByAppendingPathExtension:@"txt"];
NSLog(@"str = %@",str);
//stringByDeletingLastPathComponent Property
//stringByDeletingPathExtension Property
str = [str stringByDeletingPathExtension];
str = [str stringByDeletingLastPathComponent];
NSLog(@"str = %@",str);
//stringByExpandingTildeInPath Property
str = str.stringByAbbreviatingWithTildeInPath;
NSLog(@"str = %@",str);
str = str.stringByExpandingTildeInPath;
NSLog(@"str = %@",str);
//stringByResolvingSymlinksInPath Property
str = @"~/a.txt";
NSLog(@"str.stringByResolvingSymlinksInPath = %@", str.stringByResolvingSymlinksInPath);
//stringByStandardizingPath Property
NSLog(@"str.stringByStandardizingPath = %@", str.stringByStandardizingPath);
//- stringsByAppendingPaths:
arr = @[@"a", @"b", @"c", @"d"];
arr = [str stringsByAppendingPaths:arr];
NSLog(@"arr = %@", arr);
//print: arr = (
// "~/a.txt/a",
// "~/a.txt/b",
// "~/a.txt/c",
// "~/a.txt/d"
// )
////////////////////////// Working with URLs //////////////////////////
//- stringByAddingPercentEscapesUsingEncoding:
//- stringByReplacingPercentEscapesUsingEncoding:
str = @"http://218.21.213.10/MobileOA/TIFF/鄂安办发45号关于下达2012年全市安全生产相对控制指标的通知1.jpg";
str4 = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] = %@", str4);
str4 = [str4 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"str4 = %@", str4);
//- stringByAddingPercentEncodingWithAllowedCharacters:
//- stringByRemovingPercentEncoding
NSString *unescaped = @"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(@"escapedString: %@", escapedString);
escapedString = [escapedString stringByRemovingPercentEncoding];
NSLog(@"escapedString: %@", escapedString);
////////////////////////// Linguistic Tagging and Analysis 无语言学积累, 不知道怎么用啊???? 知道的盆友告诉我一下, 非常谢谢! //////////////////////////
//- enumerateLinguisticTagsInRange:scheme:options:orthography:usingBlock:
//- linguisticTagsInRange:scheme:options:orthography:tokenRanges:
#pragma mark NSMutableString
//
// NSMutableString 是 NSString 的 subClass
//
////////////////////////// Creating and Initializing a Mutable String //////////////////////////
//+ stringWithCapacity:
//- initWithCapacity:
NSMutableString *mStr = [NSMutableString stringWithCapacity:1]; //估计大小
[mStr appendString:@"aa"];
NSLog(@"mStr = %@", mStr);
////////////////////////// Modifying a String //////////////////////////
//- appendFormat:
//- appendString:
[mStr appendFormat:@"bb"];
[mStr appendString:@"cc"];
NSLog(@"mStr = %@", mStr);
//- deleteCharactersInRange:
[mStr deleteCharactersInRange:NSMakeRange(mStr.length-2, 2)];
NSLog(@"mStr = %@", mStr);
//- insertString:atIndex:
[mStr insertString:@"__" atIndex:2];
NSLog(@"mStr = %@", mStr);
//- replaceCharactersInRange:withString:
[mStr replaceCharactersInRange:NSMakeRange(2, 2) withString:@"--"];
NSLog(@"mStr = %@", mStr);
//- replaceOccurrencesOfString:withString:options:range:
[mStr replaceOccurrencesOfString:@"-" withString:@"^" options:NSLiteralSearch range:NSMakeRange(0, mStr.length)];
NSLog(@"mStr = %@", mStr);
//- setString:
[mStr setString:@"ccddee"];
NSLog(@"mStr = %@", mStr);
}
// - initWithFormat:arguments: // - initWithFormat:locale:arguments:
-(NSString*)vaListTest:(NSString*)args, ...{
va_list argList;
va_start(argList, args);
//NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@" arguments:argList];
NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@" locale:[NSLocale currentLocale] arguments:argList];
va_end(argList);
str = [NSString stringWithFormat:@"%@%@",args,str];
return str;
}
@end