三种类型 NSCFConstantString、NSCFString、NSTaggedPointerString
######1、NSCFConstantString字符串常量 NSCFConstantString对象,只要字符串内容不变,就不会分配新的内存地址,无论你是赋值、retain、copy。这种优化在大量使用NSString的情况下可以节省内存,提高性能
NSString *str1 = @"aaa";
NSString *str2 = [NSString stringWithString:@"aaa"];// XCode会提示 其实就是 str2 = @"aaa";
NSString *str3 = [[NSString alloc] initWithString:@"aaa"];// XCode会提示 其实就是 str3 = @"aaa";
// 三个都是一样,字符串常量NSCFConstantString,同一个地址
复制代码
######2、NSTaggedPointerString 当数字、英文、符号等的ASCII字符组成字符串,长度小于等于9的时候会自动成为NSTaggedPointerString类型(TaggedPointer专门用来存储小的对象)
// NSTaggedPointerString
NSString *str5 = [NSString stringWithFormat:@"123456789"];
NSString *str6 = [NSString stringWithFormat:@"123ASD"];
复制代码
NSTaggedPointerString是假对象,指针的值不再是地址了,而是真正的值。所以,实际上它不再是一个对象了,它只是一个披着对象皮的普通变量而已!所以,它的内存并不存储在堆中,也不需要malloc和free。
NSString *str1 = [NSString stringWithFormat:@"1"];
NSString *str2 = [NSString stringWithFormat:@"2"];
NSString *str3 = [NSString stringWithFormat:@"a"];
NSString *str4 = [NSString stringWithFormat:@"b"];
NSLog(@"=====%p",str1);
NSLog(@"=====%p",str2);
NSLog(@"=====%p",str3);
NSLog(@"=====%p",str4);
/*
输出 = =====0xa000000000000311 ASCII码表31就是1
输出 = =====0xa000000000000321 32就是2
输出 = =====0xa000000000000611 61就是a
输出 = =====0xa000000000000621 62就是b
*/
复制代码
#####3、NSCFString 字符串(可能是非 ASCII 字符)长度大于9的非常量字符串,是__NSCFString类型。 NSCFString对象是一种NSString子类,存储在堆上,不属于字符串常量对象。该对象创建之后和其他的Obj对象一样引用计数为1,对其执行retain和release将改变其retainCount。
NSString *str1 = [NSString stringWithFormat:@"1234567890"];
NSString *str2 = [[NSString alloc] stringWithFormat:@"123你好"];
// NSCFString对象是一种NSString子类,存储在堆上,不属于字符串常量对象。该对象创建之后和其他的Obj对象一样引用计数为1,对其执行retain和release将改变其retainCount。
复制代码
各种属性
//字符串长度
@property (readonly) NSUInteger length;
//选取字符串对应下表的字符
- (unichar)characterAtIndex:(NSUInteger)index;
复制代码
初始化方法
// 字符串的init初始化方法
- (instancetype)init NS_DESIGNATED_INITIALIZER;
// NSCoding协议-实例化序列化
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
// 指定缓冲区,编码和字节长度初始化NSString对象
- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer;
// 指定unichar字符,字节长度初始化NSString对象
- (instancetype)initWithCharacters:(constunichar *)characters length:(NSUInteger)length;
// 转化为NSString对象
- (instancetype)initWithUTF8String:(constchar *)nullTerminatedCString;
// 指定字符串初始化为NSString对象
- (instancetype)initWithString:(NSString *)aString;
// 格式化多个字符串初始化NSString对象
- (instancetype)initWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
// 格式化字符串初始化NSString对象
- (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argListNS_FORMAT_FUNCTION(1,0);
// 本地化格式化多个字符串初始化NSString对象
- (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...NS_FORMAT_FUNCTION(1,3);
// 本地化格式化字符串初始化NSString对象
- (instancetype)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argListNS_FORMAT_FUNCTION(1,0);
// 指定编码转化NSData数据
- (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
// 指定编码和字节数初始化NSString对象
- (instancetype)initWithBytes:(constvoid *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding;
// 指定缓冲区,编码和字节数初始化NSString对象
- (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer;
// 初始化空字符串
+ (instancetype)string;
// 初始化NSString字符串
+ (instancetype)stringWithString:(NSString *)string;
// 返回指定长度unichar的C字符串
+ (instancetype)stringWithCharacters:(constunichar *)characters length:(NSUInteger)length;
// 转化C字符串为UTF8串
+ (instancetype)stringWithUTF8String:(constchar *)nullTerminatedCString;
// 初始化NSString对象昂,这种创建方式会自动释放内存,很常用的一种方式
+ (instancetype)stringWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
// 初始化NSString自动释放内存,本地化
+ (instancetype)localizedStringWithFormat:(NSString *)format, ...NS_FORMAT_FUNCTION(1,2);
// 初始化C字符串并且指定编码,在这里需要手动释放内存(init)
- (instancetype)initWithCString:(constchar *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
// 初始化C字符串并且指定编码,在这里需要自动释放内存
+ (instancetype)stringWithCString:(constchar *)cString encoding:(NSStringEncoding)enc;
// 读取URL地址数据转化为字符串并且指定编码,在这里init创建需要手动释放内存,已经知道编码
- (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
// 读取FILE地址数据转化为字符串并且指定编码,同样需要手动释放内存,已经知道编码
- (instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
// 读取URL地址数据转化为字符串并且指定编码,,这里会自动释放内存,已经知道编码
+ (instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
// 读取FILE地址数据转化为字符串并且指定编码,这里也会自定释放内存,已经知道编码
+ (instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
// 读取URL地址数据转化为字符串并且指定编码,在这里init创建需要手动释放内存,不知道编码
- (instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
// 读取FILE地址数据转化为字符串并且指定编码,同样需要手动释放内存,不知道编码
- (instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
// 取URL地址数据转化为字符串并且指定编码,,这里会自动释放内存,不知道编码
+ (instancetype)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
// 读取FILE地址数据转化为字符串并且指定编码,这里也会自定释放内存,不知道编码
+ (instancetype)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
复制代码
字符串截取
/* 防止Emoji表情截取问题,应该这样子使用:
[str substringFromIndex:[str rangeOfComposedCharacterSequenceAtIndex:index].location]
[str substringToIndex:NSMaxRange([str rangeOfComposedCharacterSequenceAtIndex:index])]
[str substringWithRange:[str rangeOfComposedCharacterSequencesForRange:range]
*/
// 截取指定位置Index之后字符串
- (NSString *)substringFromIndex:(NSUInteger)from;
// 从索引0第一个字符串开始,截取指定长度的字符串
- (NSString *)substringToIndex:(NSUInteger)to;
// 截取字符串的指定段,返回值为NSString
- (NSString *)substringWithRange:(NSRange)range; // Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up character sequences
// 截取字符串的指定段
- (void)getCharacters:(unichar *)buffer range:(NSRange)range;
复制代码
字符串对比
//字符串进行比较
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
NSCaseInsensitiveSearch =1,//两个字符串的比较不区分大小写
NSLiteralSearch = 2,//两个字符串的比较区分大小写
NSBackwardsSearch =4,//从字符串末尾开发查询搜索
NSAnchoredSearch =8,//搜索有限制范围的字符串
NSNumericSearch = 64,//根据字符串里的数字来计算顺序
NSDiacriticInsensitiveSearchNS_ENUM_AVAILABLE(10_5,2_0) =128,
NSWidthInsensitiveSearch NS_ENUM_AVAILABLE(10_5,2_0) =256,//可以忽略字符串的宽度(长度)比较结果
NSForcedOrderingSearchNS_ENUM_AVAILABLE(10_5,2_0) =512,//忽略不区分大小写比较的选项
NSRegularExpressionSearchNS_ENUM_AVAILABLE(10_7,3_2) =1024 //
};
/**
比较字符串
@param string self与string比较
@param mask NSStringCompareOptions条件
@param rangeOfReceiverToCompare 指定段进行比较(只是对self)
@param locale 某些条件还有本地化语言环境
@return NSComparisonResult NSOrderedAscending大 NSOrderedSame相同 NSOrderedDescending小
*/
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale;
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
// 不区分大小写比较字符串
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
// 本地化比较字符串
- (NSComparisonResult)localizedCompare:(NSString *)string;
//不区分大小写以及本地化比较字符串
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
// 本地化标准字符串比较--它排序的方式和 Finder 一样。它对应的选项是 NSCaseInsensitiveSearch、NSNumericSearch、NSWidthInsensitiveSearch 以及 NSForcedOrderingSearch。如果我们要在 UI 上显示一个文件列表,用它就最合适不过了
/*
//OC之按中文排序(localizedStandardCompare)
NSArray *arrs=@[@"小雨",@"安安",@"小风",@"荣荣",@"张涛",@"李文荣"];
NSArray *sortarr=[arrs sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 localizedStandardCompare:obj2];//中文按照拼音的首字母排序
}];
*/
- (NSComparisonResult)localizedStandardCompare:(NSString *)string NS_AVAILABLE(10_6, 4_0);
// 判断两个字符串是否内容一致
- (BOOL)isEqualToString:(NSString *)aString;
复制代码
字符串搜索查找
// 是否包含前缀(以str开头)
- (BOOL)hasPrefix:(NSString *)str;
// 是否包含后缀(以str结尾)
- (BOOL)hasSuffix:(NSString *)str;
// 获取公共前缀 加入self=@“ABC1234” str=@“ABC789”,返回就是ABC
- (NSString *)commonPrefixWithString:(NSString *)str options:(NSStringCompareOptions)mask;
// 是否包含字符串
- (BOOL)containsString:(NSString *)str NS_AVAILABLE(10_10, 8_0);
// 本地化是否包含字符串(不区分大小写)
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str NS_AVAILABLE(10_10, 8_0);
// 本地化是否包含字符串(标准)
- (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
// 本地化搜索字符串范围(标准)
- (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
//搜索(指定字符串)
- (NSRange)rangeOfString:(NSString *)searchString;
//搜索(指定字符串,条件)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
//搜索(指定字符串,条件,范围)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
//搜索(指定字符串,条件,范围,本地化)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(nullable NSLocale *)locale;
// 搜索(指定字符集合)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;
// 搜索(指定字符集合,条件)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask;
// 搜索(指定字符集合,条件,范围)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
// 用字符串的字符编码指定索引查找位置
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
// 用字符串的字符编码指定区域段查找位置
- (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range;
复制代码
字符串转换
@property (readonly) double doubleValue;
@property (readonly) float floatValue;
@property (readonly) int intValue;
@property (readonly) NSInteger integerValue;
@property (readonly) long long longLongValue;
@property (readonly) BOOL boolValue;
//将字符串的所有字符转化成大写
@property (readonly,copy)NSString *uppercaseString;
//将字符串的所有字符转化为小写
@property (readonly,copy)NSString *lowercaseString;
// 所有单词的首字母转化成大写
@property (readonly,copy)NSString *capitalizedString;
//所有字符转化成大写 本地化
- (NSString *)uppercaseStringWithLocale:(NSLocale *)localeNS_AVAILABLE(10_8,6_0);
//所有字符串转化成小写 本地化
- (NSString *)lowercaseStringWithLocale:(NSLocale *)localeNS_AVAILABLE(10_8,6_0);
//所有单词首字母转化成大写 本地化
- (NSString *)capitalizedStringWithLocale:(NSLocale *)localeNS_AVAILABLE(10_8,6_0);
//默认本地化所有字符转化成大写
@property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
//默认本地化所有字符串转化成小写
@property (readonly, copy) NSString *localizedLowercaseString NS_AVAILABLE(10_11, 9_0);
//默认本地化所有单词首字母转化成大写
@property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
复制代码
字符串分行,分段
//分行//
//1.指定范围,分行取字符串
- (void)getLineStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)lineEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//2.获取指定范围该行的范围
- (NSRange)lineRangeForRange:(NSRange)range;
//分段//
//3.指定范围,分段取字符串
- (void)getParagraphStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)parEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//4.获取指定范围该段落的范围
- (NSRange)paragraphRangeForRange:(NSRange)range;
//字符串分行,分段//
NSString *string = @"123 456\nABC,DEF\nabc.def";
//获取该行的范围(指定范围)
NSRange range1 = [string lineRangeForRange:NSMakeRange(0, 10)];
NSLog(@"%ld 行长度: %ld", range1.location, range1.length);
//输出: 0 行长度: 16
//获取该段落范围(指定范围)
NSRange range2 = [string paragraphRangeForRange:NSMakeRange(0, 3)];
NSLog(@"%ld 段落长度: %ld", range2.location, range2.length);
//输出: 0 段落长度: 8
复制代码
字符串枚举方法
typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) {
// Pass in one of the "By" options:
NSStringEnumerationByLines = 0, // 按行
NSStringEnumerationByParagraphs = 1, // 按段落
NSStringEnumerationByComposedCharacterSequences = 2, // 按字符顺序
NSStringEnumerationByWords = 3, // 按单词,字
NSStringEnumerationBySentences = 4, // 按句子
NSStringEnumerationReverse = 1UL << 8, // 反向遍历
NSStringEnumerationSubstringNotRequired = 1UL << 9, // 不需要子字符串
NSStringEnumerationLocalized = 1UL << 10 // 本地化
};
// 检查是否在指定范围内是否有匹配的字符串
- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
// 列举枚举字符串所有行
- (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
//使用例子//
NSString *string = @"123456\nABCDEF\nabcdef
//1.列举(按行)
[string enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) {
NSLog(@"每行: %@", line);
}];
//输出: 每行: 123456
//输出: 每行: ABCDEF
//输出: 每行: abcdef
//2.列举(范围,条件)
[string enumerateSubstringsInRange:NSMakeRange(5, 10) options:NSStringEnumerationByLines usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
NSLog(@"%@", substring);
NSLog(@"%ld %ld", substringRange.location, substringRange.length);
NSLog(@"%ld %ld", enclosingRange.location, enclosingRange.length);
}];
//输出: 6
//输出: 5 1
//输出: 5 2
//输出: ABCDEF
//输出: 7 6
//输出: 7 7
//输出: a
//输出: 14 1
//输出: 14 1
复制代码
编码相关
NS_ENUM(NSStringEncoding) {
NSASCIIStringEncoding = 1, /* 0..127 only */
NSNEXTSTEPStringEncoding = 2,
NSJapaneseEUCStringEncoding = 3,
NSUTF8StringEncoding = 4,
NSISOLatin1StringEncoding = 5,
NSSymbolStringEncoding = 6,
NSNonLossyASCIIStringEncoding = 7,
NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
NSISOLatin2StringEncoding = 9,
NSUnicodeStringEncoding = 10,
NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
NSWindowsCP1253StringEncoding = 13, /* Greek */
NSWindowsCP1254StringEncoding = 14, /* Turkish */
NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
NSMacOSRomanStringEncoding = 30,
NSUTF16StringEncoding = NSUnicodeStringEncoding, /* An alias for NSUnicodeStringEncoding */
NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF32StringEncoding = 0x8c000100,
NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
NSUTF32LittleEndianStringEncoding = 0x9c000100 /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
// UTF8编码值
@property (nullable, readonly) const char *UTF8String;
// 最快编码值
@property (readonly) NSStringEncoding fastestEncoding;
// 自小编码值
@property (readonly) NSStringEncoding smallestEncoding;
// 选择编码,是否允许有损编码
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy;
// 选择编码
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding;
// 判断是否可以无损编码
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding;
// C字符编码转换
- (nullable const char *)cStringUsingEncoding:(NSStringEncoding)encoding ;
// 判断C字符转化是否可以成功
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding;
// 指定缓存区转换
- (BOOL)getBytes:(nullable void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(nullable NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(nullable NSRangePointer)leftover;
// 对字符串进行编码时所需的最大字节数
- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc;
// 对字符串进行编码时所需的字节数
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc;
// 可用字符串编码
+ (const NSStringEncoding *)availableStringEncodings;
// 本地化编码名称
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding;
// 默认C字符串编码
+ (NSStringEncoding)defaultCStringEncoding;
// unicode范式D标准化
@property (readonly,copy)NSString *decomposedStringWithCanonicalMapping;
// unicode范式c标准化
@property (readonly,copy)NSString *precomposedStringWithCanonicalMapping;
// unicode范式KD标准化
@property (readonly,copy)NSString *decomposedStringWithCompatibilityMapping;
// unicode范式KC标准化
@property (readonly,copy)NSString *precomposedStringWithCompatibilityMapping;
复制代码
字符串分割
/*
NSCharacterSet
controlCharacterSet 控制符
whitespaceCharacterSet 空格符
whitespaceAndNewlineCharacterSet 空格换行符
decimalDigitCharacterSet 小数
letterCharacterSet 文字
lowercaseLetterCharacterSet 小写字母
uppercaseLetterCharacterSet 大写字母
nonBaseCharacterSet 非基础
alphanumericCharacterSet 数字字母
decomposableCharacterSet 可分解
illegalCharacterSet 非法
punctuationCharacterSet 标点
capitalizedLetterCharacterSet 大写
symbolCharacterSet 符号
newlineCharacterSet 换行符
*/
//分割(指定字符串)
- (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator;
//分割(指定字符集合)
- (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NS_AVAILABLE(10_5, 2_0);
//使用例子//
NSString *string = @"A_B_c_D_E_F";
//分割(指定字符串)
NSArray *resultArr1 = [string componentsSeparatedByString:@"_"];
NSLog(@"%@", resultArr1);
//输出: (A, B, c, D, E, F)
//分割(指定字符集合)
NSArray *resultArr2 = [string componentsSeparatedByCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
NSLog(@"%@", resultArr2);
//输出: ("A_B_" , "_D_E_F")
复制代码
字符串操作(修剪,填充,折叠,替换)
NSString *string = @"3EWRs a;af";
//修剪//
NSString *result1 = [string stringByTrimmingCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
NSLog(@"%@", result1);
//输出: 3EWRs a;
//填充//
NSString *result2 = [string stringByPaddingToLength:20 withString:@"填充" startingAtIndex:1];
NSLog(@"%@", result2);
//输出: 3EWRs a;af充填充填充填充填充填
//折叠//
NSString *result3 = [string stringByFoldingWithOptions:NSNumericSearch locale:[NSLocale systemLocale]];
NSLog(@"%@", result3);
//输出: 3EWRs a;af
//替换//
//替换(指定字符串)
NSString *result4 = [string stringByReplacingOccurrencesOfString:@" " withString:@"替换"];
NSLog(@"%@", result4);
//输出: 3EWRs替换a;af
//替换(指定字符串,条件,范围)
NSString *result5 = [string stringByReplacingOccurrencesOfString:@"a" withString:@"替换" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length - 2)];
NSLog(@"%@", result5);
//输出: 3EWRs 替换;af
//替换(指定范围)
NSString *result6 = [string stringByReplacingCharactersInRange:NSMakeRange(0, string.length) withString:@"替换"];
NSLog(@"%@", result6);
//输出: 替换
复制代码
字符串翻译
//翻译选择
NSStringTransformLatinToKatakana 拉丁->片假名
NSStringTransformLatinToHiragana 拉丁->平假名
NSStringTransformLatinToHangul 拉丁->韩语
NSStringTransformLatinToArabic 拉丁->阿拉伯语
NSStringTransformLatinToHebrew 拉丁->希伯来语
NSStringTransformLatinToThai 拉丁->泰国
NSStringTransformLatinToCyrillic 拉丁->西里尔字母
NSStringTransformLatinToGreek 拉丁->希腊
NSStringTransformToLatin 拉丁
NSStringTransformMandarinToLatin 普通话->拉丁
NSStringTransformHiraganaToKatakana 平假名->片假名
NSStringTransformFullwidthToHalfwidth 全角->半角
NSStringTransformToXMLHex XML16进制
NSStringTransformToUnicodeName Unicode名
NSStringTransformStripCombiningMarks 结合地带商标
NSStringTransformStripDiacritics 带音符
//字符串翻译//
NSString *dalian = @"大连";
NSString *result = [dalian stringByApplyingTransform:NSStringTransformMandarinToLatin reverse:NO];
NSLog(@"%@", result);
//输出: dà lián
复制代码
字符串写入
//字符串写入//
//写入到指定路径,编码的文件中
[string writeToFile:@"/Users/Desktop/LuisX.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
//写入到指定URL,编码的文件中
[string writeToURL:[NSURL URLWithString:@"file://LuisX.text"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
复制代码
NSMutableString
NSMutableString *str = [NSMutableString stringWithString:@"string"];
//插入//
[str insertString:@"123" atIndex:2];
NSLog(@"%@", str);
//输出: st123ring
//删除//
[str deleteCharactersInRange:NSMakeRange(2, 2)];
NSLog(@"%@", str);
//输出: st3ring
//拼接//
[str appendString:@"456"];
NSLog(@"%@", str);
//输出: st3ring456
//格式化拼接//
[str appendFormat:@"7 89"];
NSLog(@"%@", str);
//输出: st3ring4567 89
//设置新字符串//
[str setString:@"string"];
NSLog(@"%@", str);
//输出: string
//字符串替换//
//1.指定范围替换
[str1 replaceCharactersInRange:NSMakeRange(2, 2) withString:@"123"];
NSLog(@"%@", str1);
//输出: st123ng
//2.指定字符串,条件,范围替换
[str1 replaceOccurrencesOfString:@"123" withString:@"--" options:NSRegularExpressionSearch range:NSMakeRange(0, str1.length)];
NSLog(@"%@", str1);
//输出: st--ng
复制代码
全部来自玩转NSString