Inherits from | |
Conforms to | |
Framework | /System/Library/Frameworks/Foundation.framework |
Availability | Available in Mac OS X v10.0 and later. |
Declared in | NSPathUtilities.h NSString.h NSURL.h |
Companion guides | |
Related sample code |
The NSString
class declares the programmatic interface for an object that manages immutable strings. (An immutable string is a text string that is defined when it is created and subsequently cannot be changed. NSString
is implemented to represent an array of Unicode characters (in other words, a text string).
The mutable subclass of NSString
is NSMutableString
.
The NSString
class has two primitive methods—length
and characterAtIndex:
—that provide the basis for all other methods in its interface. The length
method returns the total number of Unicode characters in the string. characterAtIndex:
gives access to each character in the string by index, with index values starting at 0
.
NSString
declares methods for finding and comparing strings. It also declares methods for reading numeric values from strings, for combining strings in various ways, and for converting a string to different forms (such as encoding and case changes).
The Application Kit also uses NSParagraphStyle
and its subclass NSMutableParagraphStyle
to encapsulate the paragraph or ruler attributes used by the NSAttributedString
classes. Additionally, methods to support string drawing are described in NSString Application Kit Additions Reference, found in the Application Kit.
NSString
is “toll-free bridged” with its Core Foundation counterpart, CFString (see CFStringRef
). This means that the Core Foundation type is interchangeable in function or method calls with the bridged Foundation object. Therefore, in a method where you see an NSString *
parameter, you can pass a CFStringRef
, and in a function where you see a CFStringRef
parameter, you can pass an NSString
instance (you cast one type to the other to suppress compiler warnings). This also applies to your concrete subclasses of NSString
. See Interchangeable Data Types for more information on toll-free bridging.
NSString
objects represent character strings in frameworks. Representing strings as objects allows you to use strings wherever you use other objects. It also provides the benefits of encapsulation, so that string objects can use whatever encoding and storage are needed for efficiency while simply appearing as arrays of characters. The cluster’s two public classes, NSString
and NSMutableString
, declare the programmatic interface for non-editable and editable strings, respectively.
Note: An immutable string is a text string that is defined when it is created and subsequently cannot be changed. An immutable string is implemented as an array of Unicode characters (in other words, a text string). To create and manage an immutable string, use the NSString
class. To construct and manage a string that can be changed after it has been created, use NSMutableString
.
The objects you create using NSString
and NSMutableString
are referred to as string objects (or, when no confusion will result, merely as strings). The term C string refers to the standard char *
type. Because of the nature of class clusters, string objects aren’t actual instances of the NSString
or NSMutableString
classes but of one of their private subclasses. Although a string object’s class is private, its interface is public, as declared by these abstract superclasses, NSString
and NSMutableString
. The string classes adopt the NSCopying
and NSMutableCopying
protocols, making it convenient to convert a string of one type to the other.
A string object presents itself as an array of Unicode characters (Unicode is a registered trademark of Unicode, Inc.). You can determine how many characters a string object contains with the length
method and can retrieve a specific character with the characterAtIndex:
method. These two “primitive” methods provide basic access to a string object.
Most use of strings, however, is at a higher level, with the strings being treated as single entities: You compare strings against one another, search them for substrings, combine them into new strings, and so on. If you need to access string objects character by character, you must understand the Unicode character encoding, specifically issues related to composed character sequences. For details see The Unicode Standard, Version 4.0 (The Unicode Consortium, Boston: Addison-Wesley, 2003, ISBN 0-321-18578-1) and the Unicode Consortium web site: http://www.unicode.org/. See also Characters and Grapheme Clusters in String Programming Guide for Cocoa.
When creating an NSString
object from a UTF-16-encoded string (or a byte stream interpreted as UTF-16), if the byte order is not otherwise specified, NSString
assumes that the UTF-16 characters are big-endian, unless there is a BOM (byte-order mark), in which case the BOM dictates the byte order. When creating an NSString
object from an array of Unicode characters, the returned string is always native-endian, since the array always contains Unicode characters in native byte order.
Over distributed-object connections, mutable string objects are passed by-reference and immutable string objects are passed by-copy.
It is possible to subclass NSString
(and NSMutableString
), but doing so requires providing storage facilities for the string (which is not inherited by subclasses) and implementing two primitive methods. The abstract NSString
and NSMutableString
classes are the public interface of a class cluster consisting mostly of private, concrete classes that create and return a string object appropriate for a given situation. Making your own concrete subclass of this cluster imposes certain requirements (discussed in “Methods to Override”).
Make sure your reasons for subclassing NSString
are valid. Instances of your subclass should represent a string and not something else. Thus the only attributes the subclass should have are the length of the character buffer it’s managing and access to individual characters in the buffer. Valid reasons for making a subclass of NSString
include providing a different backing store (perhaps for better performance) or implementing some aspect of object behavior differently, such as memory management. If your purpose is to add non-essential attributes or metadata to your subclass of NSString
, a better alternative would be object composition (see “Alternatives to Subclassing”). Cocoa already provides an example of this with the NSAttributedString
class.
Any subclass of NSString
must override the primitive instance methods length
and characterAtIndex:
. These methods must operate on the backing store that you provide for the characters of the string. For this backing store you can use a static array, a dynamically allocated buffer, a standard NSString
object, or some other data type or mechanism. You may also choose to override, partially or fully, any other NSString
method for which you want to provide an alternative implementation. For example, for better performance it is recommended that you override getCharacters:range:
and give it a faster implementation.
You might want to implement an initializer for your subclass that is suited to the backing store that the subclass is managing. The NSString
class does not have a designated initializer, so your initializer need only invoke the init
method of super
. The NSString
class adopts the NSCopying
, NSMutableCopying
, and NSCoding
protocols; if you want instances of your own custom subclass created from copying or coding, override the methods in these protocols.
Note that you shouldn’t override the hash
method.
Often a better and easier alternative to making a subclass of NSString
—or of any other abstract, public class of a class cluster, for that matter—is object composition. This is especially the case when your intent is to add to the subclass metadata or some other attribute that is not essential to a string object. In object composition, you would have an NSString
object as one instance variable of your custom class (typically a subclass of NSObject
) and one or more instance variables that store the metadata that you want for the custom object. Then just design your subclass interface to include accessor methods for the embedded string object and the metadata.
If the behavior you want to add supplements that of the existing class, you could write a category on NSString
. Keep in mind, however, that this category will be in effect for all instances of NSString
that you use, and this might have unintended consequences.
+ string
– init
– initWithBytes:length:encoding:
– initWithBytesNoCopy:length:encoding:freeWhenDone:
– initWithCharacters:length:
– initWithCharactersNoCopy:length:freeWhenDone:
– initWithString:
– initWithCString:encoding:
– initWithUTF8String:
– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
– initWithData:encoding:
+ stringWithFormat:
+ localizedStringWithFormat:
+ stringWithCharacters:length:
+ stringWithString:
+ stringWithCString:encoding:
+ stringWithUTF8String:
+ stringWithCString:
Deprecated in Mac OS X v10.4
+ stringWithCString:length:
Deprecated in Mac OS X v10.4
– initWithCString:
Deprecated in Mac OS X v10.4
– initWithCString:length:
Deprecated in Mac OS X v10.4
– initWithCStringNoCopy:length:freeWhenDone:
Deprecated in Mac OS X v10.4
+ stringWithContentsOfFile:encoding:error:
– initWithContentsOfFile:encoding:error:
+ stringWithContentsOfFile:usedEncoding:error:
– initWithContentsOfFile:usedEncoding:error:
+ stringWithContentsOfFile:
Deprecated in Mac OS X v10.4
– initWithContentsOfFile:
Deprecated in Mac OS X v10.4
+ stringWithContentsOfURL:encoding:error:
– initWithContentsOfURL:encoding:error:
+ stringWithContentsOfURL:usedEncoding:error:
– initWithContentsOfURL:usedEncoding:error:
+ stringWithContentsOfURL:
Deprecated in Mac OS X v10.4
– initWithContentsOfURL:
Deprecated in Mac OS X v10.4
– writeToFile:atomically:encoding:error:
– writeToURL:atomically:encoding:error:
– writeToFile:atomically:
Deprecated in Mac OS X v10.4
– writeToURL:atomically:
Deprecated in Mac OS X v10.4
– characterAtIndex:
– getCharacters:
– getCharacters:range:
– getBytes:maxLength:usedLength:encoding:options:range:remainingRange:
– cStringUsingEncoding:
– getCString:maxLength:encoding:
– UTF8String
– cString
Deprecated in Mac OS X v10.4
– cStringLength
Deprecated in Mac OS X v10.4
– getCString:
Deprecated in Mac OS X v10.4
– getCString:maxLength:
Deprecated in Mac OS X v10.4
– getCString:maxLength:range:remainingRange:
Deprecated in Mac OS X v10.4
– lossyCString
Deprecated in Mac OS X v10.4
– stringByAppendingFormat:
– stringByAppendingString:
– stringByPaddingToLength:withString:startingAtIndex:
– componentsSeparatedByString:
– componentsSeparatedByCharactersInSet:
– stringByTrimmingCharactersInSet:
– substringFromIndex:
– substringWithRange:
– substringToIndex:
– rangeOfCharacterFromSet:
– rangeOfCharacterFromSet:options:
– rangeOfCharacterFromSet:options:range:
– rangeOfString:
– rangeOfString:options:
– rangeOfString:options:range:
– rangeOfString:options:range:locale:
– stringByReplacingOccurrencesOfString:withString:
– stringByReplacingOccurrencesOfString:withString:options:range:
– stringByReplacingCharactersInRange:withString:
– getLineStart:end:contentsEnd:forRange:
– lineRangeForRange:
– getParagraphStart:end:contentsEnd:forRange:
– paragraphRangeForRange:
– caseInsensitiveCompare:
– localizedCaseInsensitiveCompare:
– compare:
– localizedCompare:
– compare:options:
– compare:options:range:
– compare:options:range:locale:
– hasPrefix:
– hasSuffix:
– isEqualToString:
– hash
– decomposedStringWithCanonicalMapping
– decomposedStringWithCompatibilityMapping
– precomposedStringWithCanonicalMapping
– precomposedStringWithCompatibilityMapping
+ availableStringEncodings
+ defaultCStringEncoding
+ localizedNameOfStringEncoding:
– canBeConvertedToEncoding:
– dataUsingEncoding:
– dataUsingEncoding:allowLossyConversion:
– description
– fastestEncoding
– smallestEncoding
+ pathWithComponents:
– pathComponents
– completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:
– fileSystemRepresentation
– getFileSystemRepresentation:maxLength:
– isAbsolutePath
– lastPathComponent
– pathExtension
– stringByAbbreviatingWithTildeInPath
– stringByAppendingPathComponent:
– stringByAppendingPathExtension:
– stringByDeletingLastPathComponent
– stringByDeletingPathExtension
– stringByExpandingTildeInPath
– stringByResolvingSymlinksInPath
– stringByStandardizingPath
– stringsByAppendingPaths:
Returns a zero-terminated list of the encodings string objects support in the application’s environment.
+ (const NSStringEncoding *)availableStringEncodings
A zero-terminated list of the encodings string objects support in the application’s environment.
Among the more commonly used encodings are:
See the “Constants” section for a larger list and descriptions of many supported encodings. In addition to those encodings listed here, you can also use the encodings defined for CFString in Core Foundation; you just need to call the CFStringConvertEncodingToNSStringEncoding
function to convert them to a usable format.
NSString.h
Returns the C-string encoding assumed for any method accepting a C string as an argument.
+ (NSStringEncoding)defaultCStringEncoding
The C-string encoding assumed for any method accepting a C string as an argument.
This method returns a user-dependent encoding who value is derived from user's default language and potentially other factors. You might sometimes need to use this encoding when interpreting user documents with unknown encodings, in the absence of other hints, but in general this encoding should be used rarely, if at all. Note that some potential values might result in unexpected encoding conversions of even fairly straightforward NSString
content—for example, punctuation characters with a bidirectional encoding.
Methods that accept a C string as an argument use ...CString...
in the keywords for such arguments: for example, stringWithCString:
—note, though, that these are deprecated. The default C-string encoding is determined from system information and can’t be changed programmatically for an individual process. See “String Encodings” for a full list of supported encodings.
NSString.h
Returns a human-readable string giving the name of a given encoding.
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
A string encoding.
A human-readable string giving the name of encoding in the current locale’s language.
NSString.h
Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the user's default locale.
+ (id)localizedStringWithFormat:(NSString *)format ...
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
A comma-separated list of arguments to substitute into format.
A string created by using format as a template into which the following argument values are substituted according to the formatting information to the user's default locale.
This method is equivalent to using initWithFormat:locale:
and passing [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]
as the locale argument.
As an example of formatting, this method replaces the decimal according to the locale in %f
and %d
substitutions, and calls descriptionWithLocale:
instead of description
where necessary.
This code excerpt creates a string from another string and a float:
NSString *myString = [NSString localizedStringWithFormat:@"%@: %f\n", @"Cost", 1234.56]; |
The resulting string has the value “Cost: 1234.560000\n
” if the locale is en_US
, and “Cost: 1234,560000\n
” if the locale is fr_FR
.
See Formatting String Objects for more information.
NSString.h
Returns a string built from the strings in a given array by concatenating them with a path separator between each pair.
+ (NSString *)pathWithComponents:(NSArray *)components
An array of NSString
objects representing a file path. To create an absolute path, use a slash mark (“/
”) as the first component. To include a trailing path divider, use an empty string as the last component.
A string built from the strings in components by concatenating them (in the order they appear in the array) with a path separator between each pair.
This method doesn’t clean up the path created; use stringByStandardizingPath
to resolve empty components, references to the parent directory, and so on.
NSPathUtilities.h
Returns an empty string.
+ (id)string
An empty string.
NSString.h
Returns a string containing a given number of characters taken from a given C array of Unicode characters.
+ (id)stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
A C array of Unicode characters; the value must not be NULL
.
The number of characters to use from chars.
A string containing length Unicode characters taken (starting with the first) from chars.
NSString.h
Returns a string created by reading data from the file at a given path interpreted using a given encoding.
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
A path to a file.
The encoding of the file at path.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, pass in NULL
.
A string created by reading data from the file named by path using the encoding, enc. If the file can’t be opened or there is an encoding error, returns nil
.
NSString.h
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.
+ (id)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
A path to a file.
Upon return, if the file is read successfully, contains the encoding used to interpret the file at path.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, you may pass in NULL
.
A string created by reading data from the file named by path. If the file can’t be opened or there is an encoding error, returns nil
.
This method attempts to determine the encoding of the file at path.
NSString.h
Returns a string created by reading data from a given URL interpreted using a given encoding.
+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
The URL to read.
The encoding of the data at url.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, you may pass in NULL
.
A string created by reading data from URL using the encoding, enc. If the URL can’t be opened or there is an encoding error, returns nil
.
NSString.h
Returns a string created by reading data from a given URL and returns by reference the encoding used to interpret the data.
+ (id)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
The URL from which to read data.
Upon return, if url is read successfully, contains the encoding used to interpret the data.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, you may pass in NULL
.
A string created by reading data from url. If the URL can’t be opened or there is an encoding error, returns nil
.
This method attempts to determine the encoding at url.
NSString.h
Returns a string containing the bytes in a given C array, interpreted according to a given encoding.
+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc
A C array of bytes. The array must end with a NULL
character; intermediate NULL
characters are not allowed.
The encoding of cString.
A string containing the characters described in cString.
If cString is not a NULL
-terminated C string, or encoding does not match the actual encoding, the results are undefined.
NSString.h
Returns a string created by using a given format string as a template into which the remaining argument values are substituted.
+ (id)stringWithFormat:(NSString *)format, ...
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
A comma-separated list of arguments to substitute into format.
A string created by using format as a template into which the remaining argument values are substituted according to the canonical locale.
This method is similar to localizedStringWithFormat:
, but using the canonical locale to format numbers. This is useful, for example, if you want to produce “non-localized” formatting which needs to be written out to files and parsed back later.
NSString.h
Returns a string created by copying the characters from another given string.
+ (id)stringWithString:(NSString *)aString
The string from which to copy characters. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
A string created by copying the characters from aString.
NSString.h
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
+ (id)stringWithUTF8String:(const char *)bytes
A NULL
-terminated C array of bytes in UTF8 encoding.
A string created by copying the data from bytes.
NSString.h
Returns the Boolean value of the receiver’s text.
- (BOOL)boolValue
The Boolean value of the receiver’s text. Returns YES
on encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. Returns NO
if the receiver doesn’t begin with a valid decimal text representation of a number.
The method assumes a decimal representation and skips whitespace at the beginning of the string. It also skips initial whitespace characters, or optional -/+ sign followed by zeroes.
– integerValue
– scanInt:
(NSScanner
)NSString.h
Returns a Boolean value that indicates whether the receiver can be converted to a given encoding without loss of information.
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
A string encoding.
YES
if the receiver can be converted to encoding without loss of information. Returns NO
if characters would have to be changed or deleted in the process of changing encodings.
If you plan to actually convert a string, the dataUsingEncoding:...
methods return nil
on failure, so you can avoid the overhead of invoking this method yourself by simply trying to convert the string.
NSString.h
Returns a capitalized representation of the receiver.
- (NSString *)capitalizedString
A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
A “word” here is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart:end:contentsEnd:forRange:
). Other common word delimiters such as hyphens and other punctuation aren’t considered, so this method may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercaseString
for an example.
NSString.h
Returns the result of invoking compare:options:
with NSCaseInsensitiveSearch
as the only option.
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
The string with which to compare the receiver.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
The result of invoking compare:options:
with NSCaseInsensitiveSearch
as the only option.
If you are comparing strings to present to the end-user, you should typically use localizedCaseInsensitiveCompare:
instead.
NSString.h
Returns the character at a given array position.
- (unichar)characterAtIndex:(NSUInteger)index
The index of the character to retrieve. The index value must not lie outside the bounds of the receiver.
The character at the array position given by index.
Raises an NSRangeException
if index lies beyond the end of the receiver.
NSString.h
Returns a string containing prefix the receiver and a given string have in common.
- (NSString *)commonPrefixWithString:(NSString *)aString options:(NSStringCompareOptions)mask
The string with which to compare the receiver.
Options for the comparison. The following search options may be specified by combining them with the C bitwise OR
operator: NSCaseInsensitiveSearch
, NSLiteralSearch
. See String Programming Guide for Cocoa for details on these options.
A string containing characters the receiver and aString have in common, starting from the beginning of each up to the first characters that aren’t equivalent.
The returned string is based on the characters of the receiver. For example, if the receiver is “Ma¨dchen” and aString is “Mädchenschule”, the string returned is “Ma¨dchen”, not “Mädchen”.
NSString.h
Returns the result of invoking compare:options:range:
with no options and the receiver’s full extent as the range.
- (NSComparisonResult)compare:(NSString *)aString
The string with which to compare the receiver.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
The result of invoking compare:options:range:
with no options and the receiver’s full extent as the range.
If you are comparing strings to present to the end-user, you should typically use localizedCompare:
or localizedCaseInsensitiveCompare:
instead.
– localizedCompare:
– localizedCaseInsensitiveCompare:
– compare:options:
– caseInsensitiveCompare:
– isEqualToString:
NSString.h
Returns the result of invoking compare:options:range:
with a given mask as the options and the receiver’s full extent as the range.
- (NSComparisonResult)compare:(NSString *)aString options:(NSStringCompareOptions)mask
The string with which to compare the receiver.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
Options for the search—you can combine any of the following using a C bitwise OR operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSNumericSearch
. See String Programming Guide for Cocoa for details on these options.
The result of invoking compare:options:range:
with a given mask as the options and the receiver’s full extent as the range.
If you are comparing strings to present to the end-user, you should typically use localizedCompare:
or localizedCaseInsensitiveCompare:
instead, or use compare:options:range:locale:
and pass the user’s locale.
– localizedCompare:
– localizedCaseInsensitiveCompare:
– compare:options:range:locale:
– caseInsensitiveCompare:
– isEqualToString:
NSString.h
Returns the result of invoking compare:options:range:locale:
with a nil
locale.
- (NSComparisonResult)compare:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)range
The string with which to compare the range of the receiver specified by range.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
Options for the search—you can combine any of the following using a C bitwise OR operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSNumericSearch
.
See String Programming Guide for Cocoa for details on these options.
The range of the receiver over which to perform the comparison. The range must not exceed the bounds of the receiver.
Important: Raises an NSRangeException
if range exceeds the bounds of the receiver.
The result of invoking compare:options:range:locale:
with a nil
locale.
If you are comparing strings to present to the end-user, you should typically use compare:options:range:locale:
instead and pass the user’s locale (currentLocale
[NSLocale
]).
– localizedCompare:
– localizedCaseInsensitiveCompare:
– compare:options:
– caseInsensitiveCompare:
– isEqualToString:
NSString.h
Returns an NSComparisonResult
value that indicates the lexical ordering of a specified range within the receiver and a given string.
- (NSComparisonResult)compare:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)range locale:(id)locale
The string with which to compare the range of the receiver specified by range.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
Options for the search—you can combine any of the following using a C bitwise OR operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSNumericSearch
.
See String Programming Guide for Cocoa for details on these options.
The range of the receiver over which to perform the comparison. The range must not exceed the bounds of the receiver.
Important: Raises an NSRangeException
if range exceeds the bounds of the receiver.
An instance of NSLocale
. If this value not nil
and is not an instance of NSLocale
, uses the current locale instead. If you are comparing strings to present to the end-user, you should typically pass the user’s locale (currentLocale
[NSLocale
]).
The locale argument affects both equality and ordering algorithms. For example, in some locales, accented characters are ordered immediately after the base; other locales order them after “z”.
NSOrderedAscending
if the substring of the receiver given by range precedes aString in lexical ordering for the locale given in dict, NSOrderedSame
if the substring of the receiver and aString are equivalent in lexical value, and NSOrderedDescending
if the substring of the receiver follows aString.
Prior to Mac OS X v10.5, the locale argument was an instance of NSDictionary
. On Mac OS X v10.5 and later, if you pass an instance of NSDictionary
the current locale is used instead.
– localizedCompare:
– localizedCaseInsensitiveCompare:
– caseInsensitiveCompare:
– compare:
– compare:options:
– compare:options:range:
– isEqualToString:
NSString.h
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.
- (NSUInteger)completePathIntoString:(NSString **)outputName caseSensitive:(BOOL)flag matchesIntoArray:(NSArray **)outputArray filterTypes:(NSArray *)filterTypes
Upon return, contains the longest path that matches the receiver.
If YES
, the methods considers case for possible completions.
Upon return, contains all matching filenames.
An array of NSString
objects specifying path extensions to consider for completion. only paths whose extensions (not including the extension separator) match one of those strings.
0
if no matches are found and 1
if exactly one match is found. In the case of multiple matches, returns the actual number of matching paths if outputArray is provided, or simply a positive value if outputArray is NULL
.
You can check for the existence of matches without retrieving by passing NULL
as outputArray.
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns an array containing substrings from the receiver that have been divided by characters in a given set.
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
A character set containing the characters to to use to split the receiver. Must not be nil
.
An NSArray
object containing substrings from the receiver that have been divided by characters in separator.
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator characters produce empty strings in the result. Similarly, if the string begins or ends with separator characters, the first or last substring, respectively, is empty.
NSString.h
Returns an array containing substrings from the receiver that have been divided by a given separator.
- (NSArray *)componentsSeparatedByString:(NSString *)separator
The separator string.
An NSArray
object containing substrings from the receiver that have been divided by separator.
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator string produce empty strings in the result. Similarly, if the string begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code fragment:
NSString *list = @"Norman, Stanley, Fletcher"; |
NSArray *listItems = [list componentsSeparatedByString:@", "]; |
produces an array { @"Norman", @"Stanley", @"Fletcher" }
.
If list begins with a comma and space—for example, ", Norman, Stanley, Fletcher"
—the array has these contents: { @"", @"Norman", @"Stanley", @"Fletcher" }
If list has no separators—for example, "Norman"
—the array contains the string itself, in this case { @"Norman" }
.
componentsJoinedByString:
(NSArray
)– pathComponents
NSString.h
Returns a representation of the receiver as a C string using a given encoding.
- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
The encoding for the returned C string.
A C string representation of the receiver using the encoding specified by encoding. Returns NULL
if the receiver cannot be losslessly converted to encoding.
The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current autorelease pool is emptied, whichever occurs first. You should copy the C string or use getCString:maxLength:encoding:
if it needs to store the C string beyond this time.
You can use canBeConvertedToEncoding:
to check whether a string can be losslessly converted to encoding. If it can’t, you can use dataUsingEncoding:allowLossyConversion:
to get a C-string representation using encoding, allowing some loss of information (note that the data returned by dataUsingEncoding:allowLossyConversion:
is not a strict C-string since it does not have a NULL
terminator).
– getCString:
– canBeConvertedToEncoding:
+ defaultCStringEncoding
– cStringLength
– getCharacters:
– UTF8String
NSString.h
Returns an NSData
object containing a representation of the receiver encoded using a given encoding.
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
A string encoding.
The result of invoking dataUsingEncoding:allowLossyConversion:
with NO
as the second argument (that is, requiring lossless conversion).
NSString.h
Returns an NSData
object containing a representation of the receiver encoded using a given encoding.
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
A string encoding.
If YES
, then allows characters to be removed or altered in conversion.
An NSData
object containing a representation of the receiver encoded using encoding. Returns nil
if flag is NO
and the receiver can’t be converted without losing some information (such as accents or case).
If flag is YES
and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding
to NSASCIIStringEncoding
, the character ‘Á’ becomes ‘A’, losing the accent.
This method creates an external representation (with a byte order marker, if necessary, to indicate endianness) to ensure that the resulting NSData
object can be written out to a file safely. The result of this method, when lossless conversion is made, is the default “plain text” format for encoding and is the recommended way to save or transmit a string object.
NSString.h
Returns a string made by normalizing the receiver’s contents using Form D.
- (NSString *)decomposedStringWithCanonicalMapping
A string made by normalizing the receiver’s contents using the Unicode Normalization Form D.
NSString.h
Returns a string made by normalizing the receiver’s contents using Form KD.
- (NSString *)decomposedStringWithCompatibilityMapping
A string made by normalizing the receiver’s contents using the Unicode Normalization Form KD.
NSString.h
Returns the receiver.
- (NSString *)description
The receiver.
NSString.h
Returns the floating-point value of the receiver’s text as a double
.
- (double)doubleValue
The floating-point value of the receiver’s text as a double
. Returns HUGE_VAL
or –HUGE_VAL
on overflow, 0.0 on underflow. Returns 0.0
if the receiver doesn’t begin with a valid text representation of a floating-point number.
This method skips any whitespace at the beginning of the string. This method uses formatting information stored in the non-localized value; use an NSScanner
object for localized scanning of numeric values from a string.
– floatValue
– longLongValue
– integerValue
– scanDouble:
(NSScanner
)NSString.h
Returns the fastest encoding to which the receiver may be converted without loss of information.
- (NSStringEncoding)fastestEncoding
The fastest encoding to which the receiver may be converted without loss of information.
“Fastest” applies to retrieval of characters from the string. This encoding may not be space efficient.
NSString.h
Returns a file system-specific representation of the receiver.
- (const char *)fileSystemRepresentation
A file system-specific representation of the receiver, as described for getFileSystemRepresentation:maxLength:
.
The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength:
if it needs to store the representation outside of the autorelease context in which the representation is created.
Raises an NSCharacterConversionException
if the receiver can’t be represented in the file system’s encoding.
Note that this method only works with file paths (not, for example, string representations of URLs).
To convert a char *
path (such as you might get from a C library routine) to an NSString
object, use NSFileManager
‘s stringWithFileSystemRepresentation:length:
method.
NSPathUtilities.h
Returns the floating-point value of the receiver’s text as a float
.
- (float)floatValue
The floating-point value of the receiver’s text as a float
, skipping whitespace at the beginning of the string. Returns HUGE_VAL
or –HUGE_VAL
on overflow, 0.0
on underflow. Also returns 0.0
if the receiver doesn’t begin with a valid text representation of a floating-point number.
This method uses formatting information stored in the non-localized value; use an NSScanner
object for localized scanning of numeric values from a string.
– doubleValue
– longLongValue
– integerValue
– scanFloat:
(NSScanner
)NSString.h
Gets a given range of characters as bytes in a specified encoding.
- (BOOL)getBytes:(void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(NSRangePointer)leftover
A buffer into which to store the bytes from the receiver. The returned bytes are not NULL
-terminated.
The maximum number of bytes to write to buffer.
The number of bytes used from buffer. Pass NULL
if you do not need this value.
The encoding to use for the returned bytes.
A mask to specify options to use for converting the receiver’s contents to encoding (if conversion is necessary).
The range of characters in the receiver to get.
The remaining range. Pass NULL
If you do not need this value.
YES
if some characters were converted, otherwise NO
.
Conversion might stop when the buffer fills, but it might also stop when the conversion isn't possible due to the chosen encoding.
NSString.h
Copies all characters from the receiver into a given buffer.
- (void)getCharacters:(unichar *)buffer
Upon return, contains the characters from the receiver. buffer must be large enough to contain all characters in the string ([string length]*sizeof(unichar)
).
Invokes getCharacters:range:
with buffer and the entire extent of the receiver as the range.
NSString.h
Copies characters from a given range in the receiver into a given buffer.
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange
Upon return, contains the characters from the receiver. buffer must be large enough to contain the characters in the range aRange (aRange.length*sizeof(unichar)
).
The range of characters to retrieve. The range must not exceed the bounds of the receiver.
Important: Raises an NSRangeException
if any part of aRange lies beyond the bounds of the receiver.
This method does not add a NULL
character.
The abstract implementation of this method uses characterAtIndex:
repeatedly, correctly extracting the characters, though very inefficiently. Subclasses should override it to provide a fast implementation.
NSString.h
Converts the receiver’s content to a given encoding and stores them in a buffer.
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding
Upon return, contains the converted C-string plus the NULL
termination byte. The buffer must include room for maxBufferCount bytes.
The maximum number of bytes in the string to return in buffer (including the NULL
termination byte).
The encoding for the returned C string.
YES
if the operation was successful, otherwise NO
. Returns NO
if conversion is not possible due to encoding errors or if buffer is too small.
Note that in the treatment of the maxBufferCount argument, this method differs from the deprecated getCString:maxLength: method which it replaces. (The buffer should include room for maxBufferCount bytes; this number should accommodate the expected size of the return value plus the NULL
termination byte, which this method adds.)
You can use canBeConvertedToEncoding:
to check whether a string can be losslessly converted to encoding. If it can’t, you can use dataUsingEncoding:allowLossyConversion:
to get a C-string representation using encoding, allowing some loss of information (note that the data returned by dataUsingEncoding:allowLossyConversion:
is not a strict C-string since it does not have a NULL
terminator).
NSString.h
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.
- (BOOL)getFileSystemRepresentation:(char *)buffer maxLength:(NSUInteger)maxLength
Upon return, contains a C-string that represent the receiver as as a system-independent path, plus the NULL
termination byte. The size of buffer must be large enough to contain maxLength bytes.
The maximum number of bytes in the string to return in buffer (including a terminating NULL
character, which this method adds).
YES
if buffer is successfully filled with a file-system representation, otherwise NO
(for example, if maxLength would be exceeded or if the receiver can’t be represented in the file system’s encoding).
This method operates by replacing the abstract path and extension separator characters (‘/
’ and ‘.
’ respectively) with their equivalents for the operating system. If the system-specific path or extension separator appears in the abstract representation, the characters it is converted to depend on the system (unless they’re identical to the abstract separators).
Note that this method only works with file paths (not, for example, string representations of URLs).
The following example illustrates the use of the maxLength argument. The first method invocation returns failure as the file representation of the string (@"/mach_kernel"
) is 12 bytes long and the value passed as the maxLength argument (12
) does not allow for the addition of a NULL
termination byte.
char filenameBuffer[13]; |
BOOL success; |
success = [@"/mach_kernel" getFileSystemRepresentation:filenameBuffer maxLength:12]; |
// success == NO |
// Changing the length to include the NULL character does work |
success = [@"/mach_kernel" getFileSystemRepresentation:filenameBuffer maxLength:13]; |
// success == YES |
NSPathUtilities.h
Returns by reference the beginning of the first line and the end of the last line touched by the given range.
- (void)getLineStart:(NSUInteger *)startIndex end:(NSUInteger *)lineEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:(NSRange)aRange
Upon return, contains the index of the first character of the line containing the beginning of aRange. Pass NULL
if you do not need this value (in which case the work to compute the value isn’t performed).
Upon return, contains the index of the first character past the terminator of the line containing the end of aRange. Pass NULL
if you do not need this value (in which case the work to compute the value isn’t performed).
Upon return, contains the index of the first character of the terminator of the line containing the end of aRange. Pass NULL
if you do not need this value (in which case the work to compute the value isn’t performed).
A range within the receiver. The value must not exceed the bounds of the receiver.
Important: Raises an NSRangeException
if any part of aRange lies beyond the end of the string.
A line is delimited by any of these characters, the longest possible sequence being preferred to any shorter:
U+000D
(\r
or CR
)
U+2028
(Unicode line separator)
U+000A
(\n
or LF
)
U+2029
(Unicode paragraph separator)
\r\n
, in that order (also known as CRLF
)
If aRange is contained with a single line, of course, the returned indexes all belong to that line. You can use the results of this method to construct ranges for lines by using the start index as the range’s location and the difference between the end index and the start index as the range’s length.
NSString.h
Returns by reference the beginning of the first paragraph and the end of the last paragraph touched by the given range.
- (void)getParagraphStart:(NSUInteger *)startIndex end:(NSUInteger *)endIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:(NSRange)aRange
Upon return, contains the index of the first character of the paragraph containing the beginning of aRange. Pass NULL
if you do not need this value (in which case the work to compute the value isn’t performed).
Upon return, contains the index of the first character past the terminator of the paragraph containing the end of aRange. Pass NULL
if you do not need this value (in which case the work to compute the value isn’t performed).
Upon return, contains the index of the first character of the terminator of the paragraph containing the end of aRange. Pass NULL
if you do not need this value (in which case the work to compute the value isn’t performed).
A range within the receiver. The value must not exceed the bounds of the receiver.
If aRange is contained with a single paragraph, of course, the returned indexes all belong to that paragraph. Similar to getLineStart:end:contentsEnd:forRange:
, you can use the results of this method to construct the ranges for paragraphs.
NSString.h
Returns an unsigned integer that can be used as a hash table address.
- (NSUInteger)hash
An unsigned integer that can be used as a hash table address.
If two string objects are equal (as determined by the isEqualToString:
method), they must have the same hash value. The abstract implementation of this method fulfills this requirement, so subclasses of NSString
shouldn’t override it.
You should not rely on this method returning the same hash value across releases of Mac OS X.
NSString.h
Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
- (BOOL)hasPrefix:(NSString *)aString
A string.
YES
if aString matches the beginning characters of the receiver, otherwise NO
. Returns NO
if aString is empty.
This method is a convenience for comparing strings using the NSAnchoredSearch
option. See String Programming Guide for Cocoa for more information.
NSString.h
Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver.
- (BOOL)hasSuffix:(NSString *)aString
A string.
YES
if aString matches the ending characters of the receiver, otherwise NO
. Returns NO
if aString is empty.
This method is a convenience for comparing strings using the NSAnchoredSearch
and NSBackwardsSearch
options. See String Programming Guide for Cocoa for more information.
NSString.h
Returns an initialized NSString
object that contains no characters.
- (id)init
An initialized NSString
object that contains no characters. The returned object may be different from the original receiver.
NSString.h
Returns an initialized NSString
object containing a given number of bytes from a given C array of bytes in a given encoding.
- (id)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding
A C array of bytes in the encoding specified by encoding. The array must not contain NULL
.
The number of bytes to use from bytes.
The character encoding of bytes.
An initialized NSString
object containing length bytes from bytes interpreted using the encoding encoding. The returned object may be different from the original receiver.
NSString.h
Returns an initialized NSString
object that contains a given number of bytes from a given C array of bytes in a given encoding, and optionally frees the array on deallocation.
- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)flag
A C array of bytes in the encoding specified by encoding. The array must not contain NULL
.
The number of bytes to use from bytes.
The character encoding of bytes.
If YES
, the receiver will free the memory when it no longer needs the data; if NO
it won’t.
An initialized NSString
object containing length bytes from bytes interpreted using the encoding encoding. The returned object may be different from the original receiver.
If an error occurs during the creation of the string, then bytes is not freed even if flag is YES
. In this case, the caller is responsible for freeing the buffer. This allows the caller to continue trying to create a string with the buffer, without having the buffer deallocated.
NSString.h
Returns an initialized NSString
object that contains a given number of characters from a given C array of Unicode characters.
- (id)initWithCharacters:(const unichar *)characters length:(NSUInteger)length
A C array of Unicode characters; the value must not be NULL
.
The number of characters to use from characters.
An initialized NSString
object containing length characters taken from characters. The returned object may be different from the original receiver.
NSString.h
Returns an initialized NSString
object that contains a given number of characters from a given C array of Unicode characters.
- (id)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)flag
A C array of Unicode characters.
The number of characters to use from characters.
If YES
, the receiver will free the memory when it no longer needs the characters; if NO
it won’t.
An initialized NSString
object that contains length characters from characters. The returned object may be different from the original receiver.
If an error occurs during the creation of the string, then bytes is not freed even if flag is YES
. In this case, the caller is responsible for freeing the buffer. This allows the caller to continue trying to create a string with the buffer, without having the buffer deallocated.
NSString.h
Returns an NSString
object initialized by reading data from the file at a given path using a given encoding.
- (id)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
A path to a file.
The encoding of the file at path.
If an error occurs, upon return contains an NSError
object that describes the problem. If you are not interested in possible errors, pass in NULL
.
An NSString
object initialized by reading data from the file named by path using the encoding, enc. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returns nil
.
NSString.h
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.
- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
A path to a file.
Upon return, if the file is read successfully, contains the encoding used to interpret the file at path.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, pass in NULL
.
An NSString
object initialized by reading data from the file named by path. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returns nil
.
NSString.h
Returns an NSString
object initialized by reading data from a given URL interpreted using a given encoding.
- (id)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
The URL to read.
The encoding of the file at path.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, pass in NULL
.
An NSString
object initialized by reading data from url. The returned object may be different from the original receiver. If the URL can’t be opened or there is an encoding error, returns nil
.
NSString.h
Returns an NSString
object initialized by reading data from a given URL and returns by reference the encoding used to interpret the data.
- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
The URL from which to read data.
Upon return, if url is read successfully, contains the encoding used to interpret the data.
If an error occurs, upon returns contains an NSError
object that describes the problem. If you are not interested in possible errors, pass in NULL
.
An NSString
object initialized by reading data from url. If url can’t be opened or the encoding cannot be determined, returns nil
. The returned initialized object might be different from the original receiver
NSString.h
Returns an NSString
object initialized using the characters in a given C array, interpreted according to a given encoding.
- (id)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding
A C array of characters. The array must end with a NULL
character; intermediate NULL
characters are not allowed.
The encoding of nullTerminatedCString.
An NSString
object initialized using the characters from nullTerminatedCString. The returned object may be different from the original receiver
If nullTerminatedCString is not a NULL
-terminated C string, or encoding does not match the actual encoding, the results are undefined.
NSString.h
Returns an NSString
object initialized by converting given data into Unicode characters using a given encoding.
- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding
An NSData
object containing bytes in encoding and the default plain text format (that is, pure content with no attributes or other markups) for that encoding.
The encoding used by data.
An NSString
object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil
if the initialization fails for some reason (for example if data does not represent valid data for encoding).
NSString.h
Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted.
- (id)initWithFormat:(NSString *)format ...
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
A comma-separated list of arguments to substitute into format.
An NSString object initialized by using format as a template into which the remaining argument values are substituted according to the canonical locale. The returned object may be different from the original receiver.
Invokes initWithFormat:locale:arguments:
with nil
as the locale, hence using the canonical locale to format numbers. This is useful, for example, if you want to produce "non-localized" formatting which needs to be written out to files and parsed back later.
NSString.h
Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
- (id)initWithFormat:(NSString *)format arguments:(va_list)argList
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
A list of arguments to substitute into format.
An NSString object initialized by using format as a template into which the values in argList are substituted according to the user’s default locale. The returned object may be different from the original receiver.
Invokes initWithFormat:locale:arguments:
with nil
as the locale.
NSString.h
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.
- (id)initWithFormat:(NSString *)format locale:(id)locale ...
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
This may be an instance of NSDictionary
containing locale information or an instance of NSLocale
. If this value is nil
, uses the canonical locale.
To use a dictionary containing the current user's locale, you can use [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]
.
A comma-separated list of arguments to substitute into format.
Invokes initWithFormat:locale:arguments:
with locale as the locale.
NSString.h
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.
- (id)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList
A format string. See Formatting String Objects for examples of how to use this method, and String Format Specifiers for a list of format specifiers. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
This may be an instance of NSDictionary
containing locale information or an instance of NSLocale
. If this value is nil
, uses the canonical locale.
To use a dictionary containing the current user's locale, you can use [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]
.
A list of arguments to substitute into format.
An NSString object initialized by using format as a template into which values in argList are substituted according the locale information in locale. The returned object may be different from the original receiver.
The following code fragment illustrates how to create a string from myArgs, which is derived from a string object with the value “Cost:” and an int with the value 32:
va_list myArgs; |
NSString *myString = [[NSString alloc] initWithFormat:@"%@: %d\n" |
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] |
arguments:myArgs]; |
The resulting string has the value “Cost: 32\n
”.
See String Programming Guide for Cocoa for more information.
NSString.h
Returns an NSString
object initialized by copying the characters from another given string.
- (id)initWithString:(NSString *)aString
The string from which to copy characters. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
An NSString
object initialized by copying the characters from aString. The returned object may be different from the original receiver.
NSString.h
Returns an NSString
object initialized by copying the characters a given C array of UTF8-encoded bytes.
- (id)initWithUTF8String:(const char *)bytes
A NULL
-terminated C array of bytes in UTF-8 encoding. This value must not be NULL
.
An NSString
object initialized by copying the bytes from bytes. The returned object may be different from the original receiver.
NSString.h
Returns the NSInteger
value of the receiver’s text.
- (NSInteger)integerValue
The NSInteger
value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns 0
if the receiver doesn’t begin with a valid decimal text representation of a number.
This method uses formatting information stored in the non-localized value; use an NSScanner
object for localized scanning of numeric values from a string.
– doubleValue
– floatValue
– scanInt:
(NSScanner
)NSString.h
Returns the integer value of the receiver’s text.
- (int)intValue
The integer value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns INT_MAX
or INT_MIN
on overflow. Returns 0
if the receiver doesn’t begin with a valid decimal text representation of a number.
This method uses formatting information stored in the non-localized value; use an NSScanner
object for localized scanning of numeric values from a string.
On Mac OS X v10.5 and later, use integerValue
instead.
– integerValue
– doubleValue
– floatValue
– scanInt:
(NSScanner
)NSString.h
Returning a Boolean value that indicates whether the receiver represents an absolute path.
- (BOOL)isAbsolutePath
YES
if the receiver (if interpreted as a path) represents an absolute path, otherwise NO
(if the receiver represents a relative path).
See String Programming Guide for Cocoa for more information on paths.
Note that this method only works with file paths (not, for example, string representations of URLs). The method does not check the filesystem for the existence of the path (use fileExistsAtPath:
or similar methods in NSFileManager
for that task).
NSPathUtilities.h
Returns a Boolean value that indicates whether a given string is equal to the receiver using an literal Unicode-based comparison.
- (BOOL)isEqualToString:(NSString *)aString
The string with which to compare the receiver.
YES
if aString is equivalent to the receiver (if they have the same id or if they are NSOrderedSame
in a literal comparison), otherwise NO
.
The comparison uses the canonical representation of strings, which for a particular string is the length of the string plus the Unicode characters that make up the string. When this method compares two strings, if the individual Unicodes are the same, then the strings are equal, regardless of the backing store. “Literal” when applied to string comparison means that various Unicode decomposition rules are not applied and Unicode characters are individually compared. So, for instance, “Ö” represented as the composed character sequence “O” and umlaut would not compare equal to “Ö” represented as one Unicode character.
When you know both objects are strings, this method is a faster way to check equality than isEqual:
.
NSString.h
Returns the last path component of the receiver.
- (NSString *)lastPathComponent
The last path component of the receiver.
The following table illustrates the effect of lastPathComponent
on a variety of different paths:
Receiver’s String Value |
String Returned |
---|---|
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“/” |
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns the number of Unicode characters in the receiver.
- (NSUInteger)length
The number of Unicode characters in the receiver.
The number returned includes the individual characters of composed character sequences, so you cannot use this method to determine if a string will be visible when printed or how long it will appear.
– lengthOfBytesUsingEncoding:
sizeWithAttributes:
(NSString
Additions)NSString.h
Returns the number of bytes required to store the receiver in a given encoding.
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
The encoding for which to determine the receiver's length.
The number of bytes required to store the receiver in the encoding enc in a non-external representation. The length does not include space for a terminating NULL
character.
The result is exact and is returned in O(n)
time.
NSString.h
Returns the range of characters representing the line or lines containing a given range.
- (NSRange)lineRangeForRange:(NSRange)aRange
A range within the receiver.
The range of characters representing the line or lines containing aRange, including the line termination characters.
NSString.h
Returns an NSComparisonResult
value that indicates the lexical ordering of the receiver and a given string using a case-insensitive, localized, comparison.
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
The string with which to compare the receiver.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
NSOrderedAscending
the receiver precedes aString in lexical ordering, NSOrderedSame
the receiver and aString are equivalent in lexical value, and NSOrderedDescending
if the receiver follows aString.
NSString.h
Returns an NSComparisonResult
value that indicates the lexical ordering of the receiver and another given string using a localized comparison.
- (NSComparisonResult)localizedCompare:(NSString *)aString
The string with which to compare the receiver.
This value must not be nil
. If this value is nil
, the behavior is undefined and may change in future versions of Mac OS X.
NSOrderedAscending
the receiver precedes string in lexical ordering, NSOrderedSame
the receiver and string are equivalent in lexical value, and NSOrderedDescending
if the receiver follows string.
NSString.h
Returns the long long
value of the receiver’s text.
- (long long)longLongValue
The long long
value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns LLONG_MAX
or LLONG_MIN
on overflow. Returns 0
if the receiver doesn’t begin with a valid decimal text representation of a number.
This method uses formatting information stored in the non-localized value; use an NSScanner
object for localized scanning of numeric values from a string.
– doubleValue
– floatValue
– scanInt:
(NSScanner
)NSString.h
Returns lowercased representation of the receiver.
- (NSString *)lowercaseString
A string with each character from the receiver changed to its corresponding lowercase value.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. The result of this statement:
lcString = [myString lowercaseString]; |
might not be equal to this statement:
lcString = [[myString uppercaseString] lowercaseString]; |
For example, the uppercase form of “ß” in German is “SS”, so converting “Straße” to uppercase, then lowercase, produces this sequence of strings:
“Straße”
“STRASSE”
“strasse”
NSString.h
Returns the maximum number of bytes needed to store the receiver in a given encoding.
- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
The encoding for which to determine the receiver's length.
The maximum number of bytes needed to store the receiver in encoding in a non-external representation. The length does not include space for a terminating NULL
character.
The result is an estimate and is returned in O(1)
time; the estimate may be considerably greater than the actual length needed.
NSString.h
Returns the range of characters representing the paragraph or paragraphs containing a given range.
- (NSRange)paragraphRangeForRange:(NSRange)aRange
A range within the receiver. The range must not exceed the bounds of the receiver.
The range of characters representing the paragraph or paragraphs containing aRange, including the paragraph termination characters.
NSString.h
Returns an array of NSString
objects containing, in order, each path component of the receiver.
- (NSArray *)pathComponents
An array of NSString
objects containing, in order, each path component of the receiver.
The strings in the array appear in the order they did in the receiver. If the string begins or ends with the path separator, then the first or last component, respectively, will contain the separator. Empty components (caused by consecutive path separators) are deleted. For example, this code excerpt:
NSString *path = @"tmp/scratch"; |
NSArray *pathComponents = [path pathComponents]; |
produces an array with these contents:
Index |
Path Component |
---|---|
0 |
“ |
1 |
“ |
If the receiver begins with a slash—for example, “/tmp/scratch
”—the array has these contents:
Index |
Path Component |
---|---|
0 |
“ |
1 |
“ |
2 |
“ |
If the receiver has no separators—for example, “scratch
”—the array contains the string itself, in this case “scratch
”.
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Interprets the receiver as a path and returns the receiver’s extension, if any.
- (NSString *)pathExtension
The receiver’s extension, if any (not including the extension divider).
The following table illustrates the effect of pathExtension
on a variety of different paths:
Receiver’s String Value |
String Returned |
---|---|
“ |
“ |
“ |
“” (an empty string) |
“ |
“” (an empty string) |
“ |
“ |
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a string made by normalizing the receiver’s contents using Form C.
- (NSString *)precomposedStringWithCanonicalMapping
A string made by normalizing the receiver’s contents using the Unicode Normalization Form C.
NSString.h
Returns a string made by normalizing the receiver’s contents using Form KC.
- (NSString *)precomposedStringWithCompatibilityMapping
A string made by normalizing the receiver’s contents using the Unicode Normalization Form KC.
NSString.h
Parses the receiver as a text representation of a property list, returning an NSString
, NSData
, NSArray
, or NSDictionary
object, according to the topmost element.
- (id)propertyList
A property list representation of returning an NSString
, NSData
, NSArray
, or NSDictionary
object, according to the topmost element.
The receiver must contain a string in a property list format. For a discussion of property list formats, see Property List Programming Guide.
Important: Raises an NSParseErrorException
if the receiver cannot be parsed as a property list.
NSString.h
Returns a dictionary object initialized with the keys and values found in the receiver.
- (NSDictionary *)propertyListFromStringsFileFormat
A dictionary object initialized with the keys and values found in the receiver
The receiver must contain text in the format used for .strings
files. In this format, keys and values are separated by an equal sign, and each key-value pair is terminated with a semicolon. The value is optional—if not present, the equal sign is also omitted. The keys and values themselves are always strings enclosed in straight quotation marks. Comments may be included, delimited by /*
and */
as for ANSI C comments. Here’s a short example of a strings file:
/* 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"; |
NSString.h
Finds and returns the range in the receiver of the first character from a given character set.
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
A character set. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aSet is nil
.
The range in the receiver of the first character found from aSet. Returns a range of {
NSNotFound
, 0}
if none of the characters in aSet are found.
Invokes rangeOfCharacterFromSet:options:
with no options.
NSString.h
Finds and returns the range in the receiver of the first character, using given options, from a given character set.
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask
A character set. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aSet is nil
.
A mask specifying search options. The following options may be specified by combining them with the C bitwise OR
operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSBackwardsSearch
. See String Programming Guide for Cocoa for details on these options.
The range in the receiver of the first character found from aSet. Returns a range of {
NSNotFound
, 0}
if none of the characters in aSet are found.
Invokes rangeOfCharacterFromSet:options:range:
with mask for the options and the entire extent of the receiver for the range.
NSString.h
Finds and returns the range in the receiver of the first character from a given character set found in a given range with given options.
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange
A character set. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aSet is nil
.
A mask specifying search options. The following options may be specified by combining them with the C bitwise OR
operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSBackwardsSearch
. See String Programming Guide for Cocoa for details on these options.
The range in which to search. aRange must not exceed the bounds of the receiver.
Important: Raises an NSRangeException
if any part of aRange lies beyond the end of the string.
The range in the receiver of the first character found from aSet within aRange. Returns a range of {
NSNotFound
, 0}
if none of the characters in aSet are found.
Because pre-composed characters in aSet can match composed character sequences in the receiver, the length of the returned range can be greater than 1
. For example, if you search for “ü
” in the string “stru¨del
”, the returned range is {3,2}
.
NSString.h
Returns the range in the receiver of the composed character sequence located at a given index.
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
The index of a character in the receiver. The value must not exceed the bounds of the receiver.
The range in the receiver of the composed character sequence located at anIndex.
The composed character sequence includes the first base character found at or before anIndex, and its length includes the base character and all non-base characters following the base character.
If you want to write a method to adjust an arbitrary range so it includes the composed character sequences on its boundaries, you can create a method such as the following:
- (NSRange)adjustRange:(NSRange)aRange |
{ |
NSUInteger index, endIndex; |
NSRange newRange, endRange; |
// Check for validity of range |
if ( aRange.location >= [self length] || |
aRange.location + aRange.length > [self length] ) |
{ |
[NSException raise:NSRangeException format:@"Invalid range %@.", |
NSStringFromRange(aRange)]; |
} |
index = aRange.location; |
newRange = [self rangeOfComposedCharacterSequenceAtIndex:index]; |
index = aRange.location + aRange.length - 1; |
endRange = [self rangeOfComposedCharacterSequenceAtIndex:index]; |
endIndex = endRange.location + endRange.length; |
newRange.length = endIndex - newRange.location; |
return newRange; |
} |
First, adjustRange:
corrects the location for the beginning of aRange, storing it in newRange. It then works at the end of aRange, correcting the location and storing it in endIndex. Finally, it sets the length of newRange to the difference between endIndex and the new range’s location.
NSString.h
Returns the range in the receiver of the composed character sequence in a given range.
- (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
A range in the receiver. The range must not exceed the bounds of the receiver.
The range in the receiver of the composed character sequence in range.
NSString.h
Finds and returns the range of the first occurrence of a given string within the receiver.
- (NSRange)rangeOfString:(NSString *)aString
The string to search for. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
An NSRange
structure giving the location and length in the receiver of the first occurrence of aString. Returns {
NSNotFound
, 0}
if aString is not found or is empty (@""
).
Invokes rangeOfString:options:
with no options.
NSString.h
Finds and returns the range of the first occurrence of a given string within the receiver, subject to given options.
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
The string to search for. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
A mask specifying search options. The following options may be specified by combining them with the C bitwise OR
operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSBackwardsSearch
, NSAnchoredSearch
. See String Programming Guide for Cocoa for details on these options.
An NSRange
structure giving the location and length in the receiver of the first occurrence of aString, modulo the options in mask. Returns {
NSNotFound
, 0}
if aString is not found or is empty (@""
).
Invokes rangeOfString:options:range:
with the options specified by mask and the entire extent of the receiver as the range.
NSString.h
Finds and returns the range of the first occurrence of a given string, within the given range of the receiver, subject to given options.
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange
The string for which to search. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
A mask specifying search options. The following options may be specified by combining them with the C bitwise OR
operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSBackwardsSearch
, and NSAnchoredSearch
. See String Programming Guide for Cocoa for details on these options.
The range within the receiver for which to search for aString.
Important: Raises an NSRangeException
if any part of aRange lies beyond the end of the string.
An NSRange
structure giving the location and length in the receiver of aString within aRange in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {
NSNotFound
, 0}
if aString is not found or is empty (@""
).
The length of the returned range and that of aString may differ if equivalent composed character sequences are matched.
NSString.h
Finds and returns the range of the first occurrence of a given string within a given range of the receiver, subject to given options, using the specified locale, if any.
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(NSLocale *)locale
The string for which to search. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
A mask specifying search options. The following options may be specified by combining them with the C bitwise OR
operator: NSCaseInsensitiveSearch
, NSLiteralSearch
, NSBackwardsSearch
, and NSAnchoredSearch
. See String Programming Guide for Cocoa for details on these options.
The range within the receiver for which to search for aString.
Important: Raises an NSRangeException
if any part of aRange lies beyond the end of the string.
The locale to use when comparing the receiver with aString. If this value is nil
, uses the current locale.
The locale argument affects the equality checking algorithm. For example, for the Turkish locale, case-insensitive compare matches “I” to “ı” (Unicode code point U+0131, Latin Small Dotless I), not the normal “i” character.
An NSRange
structure giving the location and length in the receiver of aString within aRange in the receiver, modulo the options in mask. The range returned is relative to the start of the string, not to the passed-in range. Returns {
NSNotFound
, 0}
if aString is not found or is empty (@""
).
The length of the returned range and that of aString may differ if equivalent composed character sequences are matched.
NSString.h
Returns the smallest encoding to which the receiver can be converted without loss of information.
- (NSStringEncoding)smallestEncoding
The smallest encoding to which the receiver can be converted without loss of information.
The returned encoding may not be the fastest for accessing characters, but is space-efficient. This method may take some time to execute.
NSString.h
Returns a new string representing the receiver as a path with a tilde (~
) substituted for the full path to the current user’s home directory.
- (NSString *)stringByAbbreviatingWithTildeInPath
A new string representing the receiver as a path with a tilde (~
) substituted for the full path to the current user’s home directory. Returns a new string matching the receiver if the receiver doesn’t begin with a user’s home directory.
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
The encoding to use for the returned string.
A representation of the receiver using encoding to determine the percent escapes necessary to convert the receiver into a legal URL string. Returns nil
if encoding cannot encode a particular character
See CFURLCreateStringByAddingPercentEscapes
for more complex transformations.
NSURL.h
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
- (NSString *)stringByAppendingFormat:(NSString *)format ...
A format string. See Formatting String Objects for more information. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if format is nil
.
A comma-separated list of arguments to substitute into format.
A string made by appending to the receiver a string constructed from format and the following arguments, in the manner of stringWithFormat:
.
NSString.h
Returns a new string made by appending to the receiver a given string.
- (NSString *)stringByAppendingPathComponent:(NSString *)aString
The path component to append to the receiver.
A new string made by appending aString to the receiver, preceded if necessary by a path separator.
The following table illustrates the effect of this method on a variety of different paths, assuming that aString is supplied as “scratch.tiff
”:
Receiver’s String Value |
Resulting String |
---|---|
“ |
“ |
“ |
“ |
“ |
“ |
“” (an empty string) |
“ |
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a new string made by appending to the receiver an extension separator followed by a given extension.
- (NSString *)stringByAppendingPathExtension:(NSString *)ext
The extension to append to the receiver.
A new string made by appending to the receiver an extension separator followed by ext.
The following table illustrates the effect of this method on a variety of different paths, assuming that ext is supplied as @"tiff"
:
Receiver’s String Value |
Resulting String |
---|---|
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
Note that adding an extension to @"/tmp/"
causes the result to be @"/tmp.tiff"
instead of @"/tmp/.tiff"
. This difference is because a file named @".tiff"
is not considered to have an extension, so the string is appended to the last nonempty path component.
This method does not allow you to append file extensions to filenames starting with the tilde character (~
).
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a new string made by appending a given string to the receiver.
- (NSString *)stringByAppendingString:(NSString *)aString
The string to append to the receiver. This value must not be nil
.
Important: Raises an NSInvalidArgumentException
if aString is nil
.
A new string made by appending aString to the receiver.
This code excerpt, for example:
NSString *errorTag = @"Error: "; |
NSString *errorString = @"premature end of file."; |
NSString *errorMessage = [errorTag stringByAppendingString:errorString]; |
produces the string “Error: premature end of file.
”.
NSString.h
Returns a new string made by deleting the last path component from the receiver, along with any final path separator.
- (NSString *)stringByDeletingLastPathComponent
A new string made by deleting the last path component from the receiver, along with any final path separator. If the receiver represents the root path it is returned unaltered.
The following table illustrates the effect of this method on a variety of different paths:
Receiver’s String Value |
Resulting String |
---|---|
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“” (an empty string) |
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a new string made by deleting the extension (if any, and only the last) from the receiver.
- (NSString *)stringByDeletingPathExtension
a new string made by deleting the extension (if any, and only the last) from the receiver. Strips any trailing path separator before checking for an extension. If the receiver represents the root path, it is returned unaltered.
The following table illustrates the effect of this method on a variety of different paths:
Receiver’s String Value |
Resulting String |
---|---|
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
“ |
Note that attempting to delete an extension from @".tiff"
causes the result to be @".tiff"
instead of an empty string. This difference is because a file named @".tiff"
is not considered to have an extension, so nothing is deleted. Note also that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a new string made by expanding the initial component of the receiver to its full path value.
- (NSString *)stringByExpandingTildeInPath
A new string made by expanding the initial component of the receiver, if it begins with “~
” or “~user
”, to its full path value. Returns a new string matching the receiver if the receiver’s initial component can’t be expanded.
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a string with the given character folding options applied.
- (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)options locale:(NSLocale *)locale
A mask of compare flags with a suffix InsensitiveSearch
.
The locale to use for the folding. The locale affects the folding logic. For example, for the Turkish locale, case-insensitive compare matches “I” to “ı” (Unicode code point U+0131, Latin Small Dotless I), not the normal “i” character.
A string with the character folding options applied.
Character folding operations remove distinctions between characters. For example, case folding may replace uppercase letters with their lowercase equivalents.
NSString.h
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.
- (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex
The new length for the receiver.
The string with which to extend the receiver.
The index in padString from which to start padding.
A new string formed from the receiver by either removing characters from the end, or by appending as many occurrences of padString as necessary.
Here are some examples of usage:
[@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0]; |
// Results in "abc......" |
[@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0]; |
// Results in "ab" |
[@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1]; |
// Results in "abc . . ." |
// Notice that the first character in the padding is " " |
NSString.h
Returns a new string in which the characters in a specified range of the receiver are replaced by a given string.
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement
A range of characters in the receiver.
The string with which to replace the characters in range.
A new string in which the characters in range of the receiver are replaced by replacement.
– stringByReplacingOccurrencesOfString:withString:
– stringByReplacingOccurrencesOfString:withString:options:range:
– stringByReplacingPercentEscapesUsingEncoding:
NSString.h
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
The string to replace.
The string with which to replace target.
A new string in which all occurrences of target in the receiver are replaced by replacement.
Invokes stringByReplacingOccurrencesOfString:withString:options:range:
with 0
options and range of the whole string.
– stringByReplacingOccurrencesOfString:withString:options:range:
– stringByReplacingCharactersInRange:withString:
– stringByReplacingPercentEscapesUsingEncoding:
NSString.h
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.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange
The string to replace.
The string with which to replace target.
A mask of options to use when comparing target with the receiver. Pass 0
to specify no options.
The range in the receiver in which to search for target.
A new string in which all occurrences of target, matched using options, in searchRange of the receiver are replaced by replacement.
– stringByReplacingOccurrencesOfString:withString:
– stringByReplacingCharactersInRange:withString:
– stringByReplacingPercentEscapesUsingEncoding:
NSString.h
Returns a new string made by replacing in the receiver all percent escapes with the matching characters as determined by a given encoding.
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
The encoding to use for the returned string.
A new string made by replacing in the receiver all percent escapes with the matching characters as determined by the given encoding encoding. Returns nil
if the transformation is not possible, for example, the percent escapes give a byte sequence not legal in encoding.
See CFURLCreateStringByReplacingPercentEscapes
for more complex transformations.
NSURL.h
Returns a new string made from the receiver by resolving all symbolic links and standardizing path.
- (NSString *)stringByResolvingSymlinksInPath
A new string made by expanding an initial tilde expression in the receiver, then resolving all symbolic links and references to current or parent directories if possible, to generate a standardized path. If the original path is absolute, all symbolic links are guaranteed to be removed; if it’s a relative path, symbolic links that can’t be resolved are left unresolved in the returned string. Returns self
if an error occurs.
If the name of the receiving path begins with /private
, the stringByResolvingSymlinksInPath
method strips off the /private
designator, provided the result is the name of an existing file.
Note that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a new string made by removing extraneous path components from the receiver.
- (NSString *)stringByStandardizingPath
A new string made by removing extraneous path components from the receiver.
If stringByStandardizingPath
detects symbolic links in a pathname, the stringByResolvingSymlinksInPath
method is called to resolve them. If an invalid pathname is provided, stringByStandardizingPath
may attempt to resolve it by calling stringByResolvingSymlinksInPath
, and the results are undefined. If any other kind of error is encountered (such as a path component not existing), self
is returned.
This method can make the following changes in the provided string:
Expand an initial tilde expression using stringByExpandingTildeInPath
.
Reduce empty components and references to the current directory (that is, the sequences “//” and “/./”) to single path separators.
In absolute paths only, resolve references to the parent directory (that is, the component “..”) to the real parent directory if possible using stringByResolvingSymlinksInPath
, which consults the file system to resolve each potential symbolic link.
In relative paths, because symbolic links can’t be resolved, references to the parent directory are left in place.
Remove an initial component of “/private
” from the path if the result still indicates an existing file or directory (checked by consulting the file system).
Note that the path returned by this method may still have symbolic link components in it. Note also that this method only works with file paths (not, for example, string representations of URLs).
NSPathUtilities.h
Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
A character set containing the characters to remove from the receiver. set must not be nil
.
A new string made by removing from both ends of the receiver characters contained in set. If the receiver is composed entirely of characters from set, the empty string is returned.
Use whitespaceCharacterSet
or whitespaceAndNewlineCharacterSet
to remove whitespace around strings.
NSString.h
Returns an array of strings made by separately appending to the receiver each string in in a given array.
- (NSArray *)stringsByAppendingPaths:(NSArray *)paths
An array of NSString
objects specifying paths to add to the receiver.
An array of NSString
objects made by separately appending each string in paths to the receiver, preceded if necessary by a path separator.
Note that this method only works with file paths (not, for example, string representations of URLs). See stringByAppendingPathComponent:
for an individual example.
NSPathUtilities.h
Returns a new string containing the characters of the receiver from the one at a given index to the end.
- (NSString *)substringFromIndex:(NSUInteger)anIndex
An index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.
Important: Raises an NSRangeException
if anIndex lies beyond the end of the receiver.
A new string containing the characters of the receiver from the one at anIndex to the end. If anIndex is equal to the length of the string, returns an empty string.
NSString.h
Returns a new string containing the characters of the receiver up to, but not including, the one at a given index.
- (NSString *)substringToIndex:(NSUInteger)anIndex
An index. The value must lie within the bounds of the receiver, or be equal to the length of the receiver.
Important: Raises an NSRangeException
if (anIndex - 1) lies beyond the end of the receiver.
A new string containing the characters of the receiver up to, but not including, the one at anIndex. If anIndex is equal to the length of the string, returns a copy of the receiver.
NSString.h
Returns a string object containing the characters of the receiver that lie within a given range.
- (NSString *)substringWithRange:(NSRange)aRange
A range. The range must not exceed the bounds of the receiver.
Important: Raises an NSRangeException
if any part of aRange lies beyond the end of the receiver.
A string object containing the characters of the receiver that lie within aRange.
This method treats the length of the string as a valid range value that returns an empty string.
NSString.h
Returns an uppercased representation of the receiver.
- (NSString *)uppercaseString
A string with each character from the receiver changed to its corresponding uppercase value.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercaseString
for an example.
NSString.h
Returns a null-terminated UTF8 representation of the receiver.
- (const char *)UTF8String
A null-terminated UTF8 representation of the receiver.
The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.
NSString.h
Writes the contents of the receiver to a file at a given path using a given encoding.
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error
The file to which to write the receiver. If path contains a tilde (~
) character, you must expand it with stringByExpandingTildeInPath
before invoking this method.
If YES
, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO
, the receiver is written directly to path. The YES
option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
The encoding to use for the output.
If there is an error, upon return contains an NSError
object that describes the problem. If you are not interested in details of errors, you may pass in NULL
.
YES
if the file is written successfully, otherwise NO
(if there was a problem writing to the file or with the encoding).
This method overwrites any existing file at path.
NSString.h
Writes the contents of the receiver to the URL specified by url using the specified encoding.
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error
The URL to which to write the receiver.
If YES
, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to url. If NO
, the receiver is written directly to url. The YES
option guarantees that url, if it exists at all, won’t be corrupted even if the system should crash during writing.
The useAuxiliaryFile parameter is ignored if url is not of a type that can be accessed atomically.
The encoding to use for the output.
If there is an error, upon return contains an NSError
object that describes the problem. If you are not interested in details of errors, you may pass in NULL
.
YES
if the URL is written successfully, otherwise NO
(if there was a problem writing to the URL or with the encoding).
NSString.h
Type for Unicode characters.
typedef unsigned short unichar;
NSString.h
A constant to define the maximum number of characters in an NSString
object. (Deprecated. This constant is not available in Mac OS X v10.5 and later.)
#define NSMaximumStringLength (INT_MAX-1)
NSMaximumStringLength
Maximum number of characters in an NSString
object.
Available in Mac OS X v10.0 through Mac OS X v10.4.
Declared in NSString.h
.
NSString.h
Type for string comparison options.
typedef NSUInteger NSStringCompareOptions;
See “Search and Comparison Options” for possible values.
NSString.h
These values represent the options available to many of the string classes’ search and comparison methods.
enum { NSCaseInsensitiveSearch = 1, NSLiteralSearch = 2, NSBackwardsSearch = 4, NSAnchoredSearch = 8, NSNumericSearch = 64, NSDiacriticInsensitiveSearch = 128, NSWidthInsensitiveSearch = 256, NSForcedOrderingSearch = 512 };
NSCaseInsensitiveSearch
A case-insensitive search.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSLiteralSearch
Exact character-by-character equivalence.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSBackwardsSearch
Search from end of source string.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSAnchoredSearch
Search is limited to start (or end, if NSBackwardsSearch
) of source string.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSNumericSearch
Numbers within strings are compared using numeric value, that is, Foo2.txt
< Foo7.txt
< Foo25.txt
.
This option only applies to compare methods, not find.
Available in Mac OS X v10.3 and later.
Declared in NSString.h
.
NSDiacriticInsensitiveSearch
Search ignores diacritic marks.
For example, ‘ö’ is equal to ‘o’.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSWidthInsensitiveSearch
Search ignores width differences in characters that have full-width and half-width forms, as occurs in East Asian character sets.
For example, with this option, the full-width Latin small letter 'a' (Unicode code point U+FF41) is equal to the basic Latin small letter 'a' (Unicode code point U+0061).
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSForcedOrderingSearch
Comparisons are forced to return either NSOrderedAscending
or NSOrderedDescending
if the strings are equivalent but not strictly equal.
This option gives stability when sorting. For example, “aaa” is greater than "AAA” if NSCaseInsensitiveSearch
is specified.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
See Searching, Comparing, and Sorting Strings for details on the effects of these options.
NSString.h
Type for encoding conversion options.
typedef NSUInteger NSStringEncodingConversionOptions;
See NSStringEncodingConversionOptions
for possible values.
NSString.h
Options for converting string encodings.
enum { NSStringEncodingConversionAllowLossy = 1, NSStringEncodingConversionExternalRepresentation = 2 };
NSStringEncodingConversionAllowLossy
Allows lossy conversion.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSStringEncodingConversionExternalRepresentation
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
These constants are available in Mac OS X v10.4; they are, however, differently named:
typedef enum { |
NSAllowLossyEncodingConversion = 1, |
NSExternalRepresentationEncodingConversion = 2 |
} NSStringEncodingConversionOptions; |
You can use them on Mac OS X v10.4 if you define the symbols as extern
constants.
NSString.h
These constants define the names of exceptions raised if NSString
cannot represent a string in a given encoding, or parse a string as a property list.
extern NSString *NSParseErrorException; extern NSString *NSCharacterConversionException;
NSCharacterConversionException
NSString
raises an NSCharacterConversionException
if a string cannot be represented in a file-system or string encoding.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSParseErrorException
NSString
raises an NSParseErrorException
if a string cannot be parsed as a property list.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSString.h
Type for string encoding.
typedef NSUInteger NSStringEncoding;
See “String Encodings” for possible values.
NSString.h
The following constants are provided by NSString
as possible string encodings.
enum { NSASCIIStringEncoding = 1, NSNEXTSTEPStringEncoding = 2, NSJapaneseEUCStringEncoding = 3, NSUTF8StringEncoding = 4, NSISOLatin1StringEncoding = 5, NSSymbolStringEncoding = 6, NSNonLossyASCIIStringEncoding = 7, NSShiftJISStringEncoding = 8, NSISOLatin2StringEncoding = 9, NSUnicodeStringEncoding = 10, NSWindowsCP1251StringEncoding = 11, NSWindowsCP1252StringEncoding = 12, NSWindowsCP1253StringEncoding = 13, NSWindowsCP1254StringEncoding = 14, NSWindowsCP1250StringEncoding = 15, NSISO2022JPStringEncoding = 21, NSMacOSRomanStringEncoding = 30, NSUTF16BigEndianStringEncoding = 0x90000100, NSUTF16LittleEndianStringEncoding = 0x94000100, NSUTF32StringEncoding = 0x8c000100, NSUTF32BigEndianStringEncoding = 0x98000100, NSUTF32LittleEndianStringEncoding = 0x9c000100, NSProprietaryStringEncoding = 65536 };
NSASCIIStringEncoding
Strict 7-bit ASCII encoding within 8-bit chars; ASCII values 0…127 only.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSISO2022JPStringEncoding
ISO 2022 Japanese encoding for email.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSISOLatin1StringEncoding
8-bit ISO Latin 1 encoding.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSISOLatin2StringEncoding
8-bit ISO Latin 2 encoding.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSJapaneseEUCStringEncoding
8-bit EUC encoding for Japanese text.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSMacOSRomanStringEncoding
Classic Macintosh Roman encoding.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSNEXTSTEPStringEncoding
8-bit ASCII encoding with NEXTSTEP extensions.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSNonLossyASCIIStringEncoding
7-bit verbose ASCII to represent all Unicode characters.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSShiftJISStringEncoding
8-bit Shift-JIS encoding for Japanese text.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSSymbolStringEncoding
8-bit Adobe Symbol encoding vector.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSUTF8StringEncoding
An 8-bit representation of Unicode characters, suitable for transmission or storage by ASCII-based systems.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSUnicodeStringEncoding
The canonical Unicode encoding for string objects.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSWindowsCP1250StringEncoding
Microsoft Windows codepage 1250; equivalent to WinLatin2.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSWindowsCP1251StringEncoding
Microsoft Windows codepage 1251, encoding Cyrillic characters; equivalent to AdobeStandardCyrillic font encoding.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSWindowsCP1252StringEncoding
Microsoft Windows codepage 1252; equivalent to WinLatin1.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSWindowsCP1253StringEncoding
Microsoft Windows codepage 1253, encoding Greek characters.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSWindowsCP1254StringEncoding
Microsoft Windows codepage 1254, encoding Turkish characters.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
NSUTF16BigEndianStringEncoding
NSUTF16StringEncoding
encoding with explicit endianness specified.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSUTF16LittleEndianStringEncoding
NSUTF16StringEncoding
encoding with explicit endianness specified.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSUTF32StringEncoding
32-bit UTF encoding.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSUTF32BigEndianStringEncoding
NSUTF32StringEncoding
encoding with explicit endianness specified.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSUTF32LittleEndianStringEncoding
NSUTF32StringEncoding
encoding with explicit endianness specified.
Available in Mac OS X v10.5 and later.
Declared in NSString.h
.
NSProprietaryStringEncoding
Installation-specific encoding.
Available in Mac OS X v10.0 and later.
Declared in NSString.h
.
These values represent the various character encodings supported by the NSString
classes. This is an incomplete list. Additional encodings are defined in Strings Programming Guide for Core Foundation (see CFStringEncodingExt.h
); these encodings can be used with NSString
by first passing the Core Foundation encoding to the CFStringConvertEncodingToNSStringEncoding
function.
NSString.h
© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-02-04)