详细的介绍iOS中字符串的相关用法

详细的介绍iOS中字符串的相关用法

Swift 其它杂项

详细介绍

NSStringUsage

字符串的使用 简书地址:https://www.jianshu.com/p/772b981bc6dd

简书个人主页:https://www.jianshu.com/u/281c41cc90bc

写这篇文章的主要原因:有时候会用到一些不常用的方法,很容易被遗忘。所以想要详细的介绍iOS中字符串的相关用法。一方面加强自己的记忆,另一方面是节省去API中寻找的时间。如果觉得这篇文章现在用得到或者未来会用到,那就添加喜欢或者收藏起来嗷!

*如果发现不够完善的地方,可以在评论区评论或者私信我,我会尽快添加

NSString(静态,纯文本Unicode字符串对象)

创建和初始化字符串(Creating and Initializing Strings)

+ string 返回空字符串(Returns an empty string.)

– init 返回不包含任何字符的初始化NSString对象(Returns an initialized NSString object that contains no characters.)

– initWithBytes:length:encoding: (Returns an initialized NSString object containing a given number of bytes from a given buffer of bytes interpreted in a given encoding.)

– initWithBytesNoCopy:length:encoding:freeWhenDone: (Returns an initialized NSString object that contains a given number of bytes from a given buffer of bytes interpreted in a given encoding, and optionally frees the buffer.)

– initWithCharacters:length: (Returns an initialized NSString object that contains a given number of characters from a given C array of UTF-16 code units.)

– initWithCharactersNoCopy:length:freeWhenDone: (Returns an initialized NSString object that contains a given number of characters from a given C array of UTF-16 code units.)

– initWithString: 返回另一个给定字符串中的字符而初始化的NSString对象(Returns an NSString object initialized by copying the characters from another given string.)

– initWithCString:encoding: (Returns an NSString object initialized using the characters in a given C array, interpreted according to a given encoding.)

– initWithUTF8String: (Returns an NSString object initialized by copying the characters from a given C array of UTF8-encoded bytes.)

– initWithFormat: (Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted.)

– initWithFormat:arguments: (Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted without any localization.)

– initWithFormat:locale: (Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale.)

– initWithFormat:locale:arguments: (Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale information. This method is meant to be called from within a variadic function, where the argument list will be available.)

– initWithData:encoding: (Returns an NSString object initialized by converting given data into UTF-16 code units using a given encoding.)

+ stringWithFormat: 通过使用给定格式字符串作为模板的字符串(Returns a string created by using a given format string as a template into which the remaining argument values are substituted.)

+ localizedStringWithFormat: (Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the current locale.)

+ localizedUserNotificationStringForKey:arguments: (Returns a localized string intended for display in a notification alert.)

+ stringWithCharacters:length: (Returns a string containing a given number of characters taken from a given C array of UTF-16 code units.)

+ stringWithString: 通过复制另一个给定字符串中的字符而创建的字符(Returns a string created by copying the characters from another given string.)

+ stringWithCString:encoding: (Returns a string containing the bytes in a given C array, interpreted according to a given encoding.)

+ stringWithUTF8String: 从给定的UTF8编码字节的C数组复制数据而创建的字符串(Returns a string created by copying the data from a given C array of UTF8-encoded bytes.)

从文件创建和初始化字符串(Creating and Initializing a String from a File)

+ stringWithContentsOfFile:encoding:error: (Returns a string created by reading data from the file at a given path interpreted using a given encoding.)

- initWithContentsOfFile:encoding:error: (Returns an NSString object initialized by reading data from the file at a given path using a given encoding.)

+ stringWithContentsOfFile:usedEncoding:error: (Returns a string created by reading data from the file at a given path and returns by reference the encoding used to interpret the file.)

- initWithContentsOfFile:usedEncoding:error: (Returns an NSString object initialized by reading data from the file at a given path and returns by reference the encoding used to interpret the characters.)

从URL创建和初始化字符串(Creating and Initializing a String from an URL)

+ stringWithContentsOfURL:encoding:error: 通过读取使用给定编码的给定URL数据而创建的字符串(Returns a string created by reading data from a given URL interpreted using a given encoding.)

- initWithContentsOfURL:encoding:error: (Returns an NSString object initialized by reading data from a given URL interpreted using a given encoding.)

+ stringWithContentsOfURL:usedEncoding:error: (Returns a string created by reading data from a given URL and returns by reference the encoding used to interpret the data.)

- initWithContentsOfURL:usedEncoding:error: (Returns an NSString object initialized by reading data from a given URL and returns by reference the encoding used to interpret the data.)

获得字符串的长度(Getting a String’s Length)

length (The number of UTF-16 code units in the receiver.)

- lengthOfBytesUsingEncoding: (Returns the number of bytes required to store the receiver in a given encoding.)

- maximumLengthOfBytesUsingEncoding: (Returns the maximum number of bytes needed to store the receiver in a given encoding.)

获取字符和字节(Getting Characters and Bytes)

- characterAtIndex: (Returns the character at a given UTF-16 code unit index.)

- getCharacters:range: (Copies characters from a given range in the receiver into a given buffer.)

- getBytes:maxLength:usedLength:encoding:options:range:remainingRange: (Gets a given range of characters as bytes in a specified encoding.)

获得C字符串(Getting C Strings)

- cStringUsingEncoding: (Returns a representation of the string as a C string using a given encoding.)

- getCString:maxLength:encoding: (Converts the string to a given encoding and stores it in a buffer.)

UIF8String (A null-terminated UTF8 representation of the string.)

识别和比较字符串(Identifying and Comparing Strings)

- caseInsensitiveCompare:

- localizedCaseInsensitiveCompare: (Compares the string with a given string using a case-insensitive, localized, comparison.)

- compare:

- localizedCompare: (Compares the string and a given string using a localized comparison.)

- compare:options: (Compares the string with the specified string using the given options.)

- compare:options:range:

- compare:options:range:locale: (Compares the string using the specified options and returns the lexical ordering for the range.)

- localizedStandardCompare: 中文按照拼音的首字母排序(Compares strings as sorted by the Finder.)

- hasPrefix: 是否以指定的前缀开始(Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.)

- hasSuffix: 是否以指定的后缀结束(Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver.)

- isEqualToString: 比较两个字符串是否相等(Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison.)

hash (An unsigned integer that can be used as a hash table address.)

NSStringCompareOptions (These values represent the options available to many of the string classes’ search and comparison methods.)

NSStringEncodingConversionOptions (Options for converting string encodings.)

拼接字符串(Combining Strings)

- stringByAppendingFormat: (Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.)

- stringByAppendingString: 字符串拼接字符串(Returns a new string made by appending a given string to the receiver.)

- stringByPaddingToLength:withString:startingAtIndex: (Returns a new string formed from the receiver by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.)

字符串大小写(Changing Case)

lowercaseString 小写字符串(A lowercase representation of the string.)

localizedLowercaseString (Returns a version of the string with all letters converted to lowercase, taking into account the current locale.)

- lowercaseStringWithLocale: 所有字母都转换成小写,要考虑制定的语言环境(Returns a version of the string with all letters converted to lowercase, taking into account the specified locale.)

uppercaseString (An uppercase representation of the string.)

localizedUppercaseString (Returns a version of the string with all letters converted to uppercase, taking into account the current locale.)

- uppercaseStringWithLocale: 所有字母都转换成大写,要考虑制定的语言环境(Returns a version of the string with all letters converted to uppercase, taking into account the specified locale.)

capitalizedString (A capitalized representation of the string.)

localizedCapitalizedString (Returns a capitalized representation of the receiver using the current locale.)

- capitalizedStringWithLocale: (Returns a capitalized representation of the receiver using the specified locale.)

字符串拆分(Dividing Strings)

- componentsSeparatedByString: (Returns an array containing substrings from the receiver that have been divided by a given separator.)

- componentsSeparatedByCharactersInSet: (Returns an array containing substrings from the receiver that have been divided by characters in a given set.)

- stringByTrimmingCharactersInSet: (Returns a new string made by removing from both ends of the receiver characters contained in a given character set.)

- substringFromIndex: 字符串截取范围是给定索引index到这个字符串的结尾(Returns a new string containing the characters of the receiver from the one at a given index to the end.)

- substringWithRange: 字符串截取范围是给定Range(Returns a string object containing the characters of the receiver that lie within a given range.)

- substringToIndex: 字符串截取范围是字符串开头到这个字符串给定索引index(Returns a new string containing the characters of the receiver up to, but not including, the one at a given index.)

规范化字符串(Normalizing Strings)

decomposedStringWithCanonicalMapping (A string made by normalizing the string’s contents using the Unicode Normalization Form D.)

decomposedStringWithCompatibilityMapping (A string made by normalizing the receiver’s contents using the Unicode Normalization Form KD.)

precomposedStringWithCanonicalMapping (A string made by normalizing the string’s contents using the Unicode Normalization Form C.)

precomposedStringWithCompatibilityMapping (A string made by normalizing the receiver’s contents using the Unicode Normalization Form KC.)

拆叠字符串(Folding Strings)

- stringByFoldingWithOptions:locale: (Creates a string suitable for comparison by removing the specified character distinctions from a string.)

转换字符串(Transforming Strings)

- stringByApplyingTransform:reverse: (Returns a new string by applying a specified transform to the string.)

NSStringTransform (Constants representing an ICU string transform.)

查找字符和子字符串(Finding Characters and Substrings)

- containsString: 查找字符串中是否包含“xxx”:方法区分小写字母(Returns a Boolean value indicating whether the string contains a given string by performing a case-sensitive, locale-unaware search.)

- localizedCaseInsensitiveContainsString: 方法不区分小写字母(Returns a Boolean value indicating whether the string contains a given string by performing a case-insensitive, locale-aware search.)

- localizedStandardContainsString: (Returns a Boolean value indicating whether the string contains a given string by performing a case and diacritic insensitive, locale-aware search.)

- rangeOfCharacterFromSet: (Finds and returns the range in the string of the first character from a given character set.)

- rangeOfCharacterFromSet:options: (Finds and returns the range in the string of the first character, using given options, from a given character set.)

- rangeOfCharacterFromSet:options:range: (Finds and returns the range in the string of the first character from a given character set found in a given range with given options.)

- rangeOfString: 判断某个字符串中是否包含指定的字符串时(Finds and returns the range of the first occurrence of a given string within the string.)

- rangeOfString:options: (Finds and returns the range of the first occurrence of a given string within the string, subject to given options.)

- rangeOfString:options:range: (Finds and returns the range of the first occurrence of a given string, within the given range of the string, subject to given options.)

- rangeOfString:options:range:locale: (Finds and returns the range of the first occurrence of a given string within a given range of the string, subject to given options, using the specified locale, if any.)

- localizedStandardRangeOfString: (Finds and returns the range of the first occurrence of a given string within the string by performing a case and diacritic insensitive, locale-aware search.)

- enumerateLinesUsingBlock: 枚举字符串所有行(Enumerates all the lines in the string.)

- enumerateSubstringsInRange:options:usingBlock: 枚举指定字符串范围内指定类型的子字符串(Enumerates the substrings of the specified type in the specified range of the string.)

替换子字符串(Replacing Substrings)

- stringByReplacingOccurrencesOfString:withString: (Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.)

- stringByReplacingOccurrencesOfString:withString:options:range: (Returns a new string in which all occurrences of a target string in a specified range of the receiver are replaced by another given string.)

- stringByReplacingCharactersInRange:withString: (Returns a new string in which the characters in a specified range of the receiver are replaced by a given string.)

- stringByReplacingCharactersInRange:withString: (Returns a new string in which the characters in a specified range of the receiver are replaced by a given string.)

获取公共的前缀(Getting a Shared Prefix)

- commonPrefixWithString:options: (Returns a string containing characters the receiver and a given string have in common, starting from the beginning of each up to the first characters that aren’t equivalent.)

语言标记分析(Performing Linguistic Analysis)

- enumerateLinguisticTagsInRange:scheme:options:orthography:usingBlock: (Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags.)

- linguisticTagsInRange:scheme:options:orthography:tokenRanges: (Returns an array of linguistic tags for the specified range and requested tags within the receiving string.)

NSStringEnumerationOptions (Constants to specify kinds of substrings and styles of enumeration.)

确定组成字符的顺序(Determining Line and Paragraph Ranges)

- getLineStart 🔚 contentsEnd:forRange: (Returns by reference the beginning of the first line and the end of the last line touched by the given range.)

- lineRangeForRange: (Returns the range of characters representing the line or lines containing a given range.)

- getParagraphStart 🔚 contentsEnd:forRange: (Returns by reference the beginning of the first paragraph and the end of the last paragraph touched by the given range.)

- paragraphRangeForRange: (Returns the range of characters representing the paragraph or paragraphs containing a given range.)

确定组成字符的顺序(Determining Composed Character Sequences)

- rangeOfComposedCharacterSequenceAtIndex: (Returns the range in the receiver of the composed character sequence located at a given index.)

- rangeOfComposedCharacterSequencesForRange: (Returns the range in the string of the composed character sequences for a given range.)

写入文件或URL(Writing to a File or URL)

- writeToFile:atomically:encoding:error: (Writes the contents of the receiver to a file at a given path using a given encoding.)

- writeToURL:atomically:encoding:error: (Writes the contents of the receiver to the URL specified by url using the specified encoding.)

将字符串内容转换成属性列表(Converting String Contents Into a Property List)

- propertyList (Parses the receiver as a text representation of a property list, returning an NSString, NSData, NSArray, or NSDictionary object, according to the topmost element.)

[- propertyListFromStringsFileFormat](https://developer.apple.com/documentation/foundation/nsstring/1407697-propertylistfromstringsfileforma?language=objc) (Returns a dictionary object initialized with the keys and values found in the receiver.)

尺寸和绘图字符串(Sizing and Drawing Strings)

- drawAtPoint:withAttributes: (Draws the receiver with the font and other display characteristics of the given attributes, at the specified point in the current graphics context.)

- drawInRect:withAttributes: (Draws the attributed string inside the specified bounding rectangle.)

- drawWithRect:options:attributes:context: (Draws the attributed string in the specified bounding rectangle using the provided options.)

- boundingRectWithSize:options:attributes:context: (Calculates and returns the bounding rect for the receiver drawn using the given options and display characteristics, within the specified rectangle in the current graphics context.)

- sizeWithAttributes: 自适应高度并返回宽高(Returns the bounding box size the receiver occupies when drawn with the given attributes.)

- variantFittingPresentationWidth: (Returns a string variation suitable for the specified presentation width.)

NSStringDrawingOptions (Constants for the rendering options for a string when it is drawn.)

字符串转换(Getting Numeric Values)

处理字符编码(Working with Encodings)

availableStringEncodings (Returns a zero-terminated list of the encodings string objects support in the application’s environment.)

defaultCStringEncoding (Returns the C-string encoding assumed for any method accepting a C string as an argument.)

+ stringEncodingForData:encodingOptions:convertedString:usedLossyConversion: (Returns the string encoding for the given data as detected by attempting to create a string according to the specified encoding options.)

+ localizedNameOfStringEncoding: (Returns a human-readable string giving the name of a given encoding.)

- canBeConvertedToEncoding: (Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information.)

- dataUsingEncoding: (Returns an NSData object containing a representation of the receiver encoded using a given encoding.)

- dataUsingEncoding:allowLossyConversion: (Returns an NSData object containing a representation of the receiver encoded using a given encoding.)

description (This NSString object.)

fastestEncoding (The fastest encoding to which the receiver may be converted without loss of information.)

fastestEncoding (The fastest encoding to which the receiver may be converted without loss of information.)

smallestEncoding (The smallest encoding to which the receiver can be converted without loss of information.)

NSStringEncoding (The following constants are provided by NSString as possible string encodings.)

NSStringEncodingDetectionOptionsKey 没有概述(No overview available.)

处理路径(Working with Paths)

+ pathWithComponents: (Returns a string built from the strings in a given array by concatenating them with a path separator between each pair.)

pathComponents (The file-system path components of the receiver.)

- completePathIntoString:caseSensitive:matchesIntoArray:filterTypes: (Interprets the receiver as a path in the file system and attempts to perform filename completion, returning a numeric value that indicates whether a match was possible, and by reference the longest path that matches the receiver.)

fileSystemRepresentation (A file system-specific representation of the receiver.)

- getFileSystemRepresentation:maxLength: (Interprets the receiver as a system-independent path and fills a buffer with a C-string in a format and encoding suitable for use with file-system calls.)

absolutePath (A Boolean value that indicates whether the receiver represents an absolute path.)

lastPathComponent (The last path component of the receiver.)

pathExtension (The path extension, if any, of the string as interpreted as a path.)

stringByAbbreviatingWithTildeInPath (A new string that replaces the current home directory portion of the current path with a tilde (~) character.)

- stringByAppendingPathComponent: (Returns a new string made by appending to the receiver a given string.)

- stringByAppendingPathExtension: (Returns a new string made by appending to the receiver an extension separator followed by a given extension.)

stringByDeletingLastPathComponent (A new string made by deleting the last path component from the receiver, along with any final path separator.)

stringByDeletingPathExtension (A new string made by deleting the extension (if any, and only the last) from the receiver.)

stringByExpandingTildeInPath (A new string made by expanding the initial component of the receiver to its full path value.)

stringByResolvingSymlinksInPath (A new string made from the receiver by resolving all symbolic links and standardizing path.)

stringByStandardizingPath (A new string made by removing extraneous path components from the receiver.)

- stringsByAppendingPaths: (Returns an array of strings made by separately appending to the receiver each string in a given array.)

处理URL(Working with URL Strings)

- stringByAddingPercentEncodingWithAllowedCharacters: (Returns a new string made from the receiver by replacing all characters not in the specified set with percent-encoded characters.)

stringByRemovingPercentEncoding (Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.)

最后,觉得有用记得给个star !非常感谢!

推荐源码