- Inherits from:
- NSObject
- Conforms to:
- NSCoding
- NSCopying
- NSMutableCopying
- NSObject (NSObject)
Declared in:
- Foundation/NSString.h
- Foundation/NSPathUtilities.h
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. An immutable string is implemented as array of Unicode characters (in other words, a text string). To create and manage a string that can be changed after it has been created, use 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). General use of these methods is presented in the section "Working with String Objects" .
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 is needed for efficiency while simply appearing as arrays of characters. The cluster's two public classes, NSString and NSMutableString, declare the programmatic interface for noneditable 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 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 it 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 3.0. The Unicode Consortium. Addison Wesley Longman, 2000. ISBN 0-201-61633-5.
NSString provides several means for creating instances, most based around the various character encodings it supports. Although string objects always present their own contents as Unicode characters, they can convert their contents to and from many other encodings, such as 7-bit ASCII, ISO Latin 1, EUC, and Shift-JIS. The availableStringEncodings class method returns the encodings supported. You can specify an encoding explicitly when converting a C string to or from a string object, or use the default C string encoding, which varies from platform to platform and is returned by the defaultCStringEncoding class method.
The simplest way to create a string object in source code is to use either the stringWithCString: class method or the initWithCString: instance method. Each takes a standard null-terminated C string in the default C string encoding and produces a string object. As a convenience, the Objective-C language also supports the @"..." construct to create a string object constant from 7-bit ASCII encoding:
NSString *temp = @"/tmp/scratch";
Such an object is created at compile time and exists throughout your program's execution. The compiler makes such object constants unique on a per-module basis, and they're never deallocated (though you can retain and release them as you do any other object).
To get a C string from a string object, use the cString message.
This returns a char *
in
the system's default string encoding, or raises an exception if
it can't convert its contents to that encoding. The C string you
receive is owned by a temporary object, though, so it will become
invalid when automatic deallocation takes place. If you want to
get a permanent C string, you must create a buffer and use one of
the getCString:... methods to fill it.
You can find out how large the buffer needs to be with the cStringLength method.
Similar methods allow you to create string objects from characters in the Unicode encoding or an arbitrary encoding, and to extract data in these encodings. initWithData:encoding: and dataUsingEncoding: perform these conversions from and to NSData objects. You can also read a string directly from a file in the Unicode or default C string encoding using the stringWithContentsOfFile: class method, and write a string using writeToFile:atomically:.
Finally, two types of method allow you to build a string from existing string objects. localizedStringWithFormat: and its siblings use a format string as a template into which the values you provide (string and other objects, numerics values, and so on) are inserted. The methods stringByAppendingString: and stringByAppendingFormat: create a new string by adding one string after another, in the second case using a format string.
In format strings, a '%' character announces a placeholder
for a value, with the characters that follow determining the kind
of value expected and how to format it. For example, a format string
of "%d houses" expects an integer value to be substituted for
the format expression "%d". NSString supports the format characters
defined for the ANSI C function printf()
,
plus '@' for any object. If the object responds to the descriptionWithLocale: message,
NSString sends that message to retrieve the text representation,
otherwise, it sends a description message.
Many compilers perform typecasting of arguments to printf()
,
so printing an integer into a %f (floating-point)
placeholder works as expected. This typecasting doesn't occur
with NSString's formatted methods, so be sure to cast your values
explicitly.
Value formatting is affected by the user's current locale, which is an NSDictionary specifying number, date, and other kinds of formats. NSString uses only the locale's definition for the decimal separator (given by the key named NSDecimalSeparator). If you use a method that doesn't specify a locale, the string assumes the default locale.
This table summarizes the most common means of creating and converting string objects:
Source | Creation Method | Extraction Method |
Default C string encoding | stringWithCString: | getCString: (or cString) |
In code | @"..." compiler construct | |
Unicode encoding | stringWithCharacters:length: | getCharacters:range: |
Arbitrary encoding | initWithData:encoding: | dataUsingEncoding: |
File contents | stringWithContentsOfFile: | writeToFile:atomically: |
Format string | localizedStringWithFormat: | initWithFormat:locale: |
Existing strings | stringByAppendingString: | stringByAppendingFormat: |
The string classes provide methods for finding characters and substrings within strings and for comparing one string to another. These methods conform to the Unicode standard for determining whether two character sequences are equivalent. The string classes provide comparison methods that handle composed character sequences properly, though you do have the option of specifying a literal search when efficiency is important and you can guarantee some canonical form for composed character sequences.
The search and comparison methods each come in three variants. The simplest version of each searches or compares entire strings. Other variants allow you to alter the way comparison of composed character sequences is performed and to specify a specific range of characters within a string to be searched or compared. You can specify these options (not all options are available for every method):
Search Option | Effect |
NSCaseInsensitiveSearch |
Ignores case distinctions among characters. |
NSLiteralSearch |
Performs a byte-for-byte comparison. Differing literal sequences (such as composed character sequences) that would otherwise be considered equivalent are considered not to match. Using this option can speed some operations dramatically. |
NSBackwardsSearch |
Performs searching from the end of the range toward the beginning. |
NSAnchoredSearch |
Performs searching only on characters at the beginning or end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of characters occurs elsewhere in the string. |
Search and comparison are currently performed as if the NSLiteralSearch
option
were specified. As the Unicode encoding becomes more widely used,
and the need for more flexible comparison increases, the default
behavior will be changed accordingly.
Substrings are only found if completely contained within the
specified range. If you specify a range for a search or comparison
method and don't request NSLiteralSearch
,
the range must not break composed character sequences on either
end; if it does you could get an incorrect result. (See the method
description for rangeOfComposedCharacterSequenceAtIndex: for
a code sample that adjusts a range to lie on character sequence
boundaries.)
The basic search and comparison methods are these:
The rangeOfString:... methods search for a substring within the receiver. The rangeOfCharacterFromSet:... methods search for individual characters from a supplied set of characters. The compare:... methods return the lexical ordering of the receiver and the supplied string. Several other methods allow you to determine whether two strings are equal or whether one is the prefix or suffix of another, but they don't have variants that allow you to specify search options or ranges.
In addition to searching and comparing strings, you can combine and divide them in various ways. The simplest way to put two strings together is to append one to the other. The stringByAppendingString: method returns a string object formed from the receiver and the argument supplied. You can also combine several strings according to a template with the initWithFormat:, stringWithFormat: and stringByAppendingFormat: methods. See "Creating and Converting String Objects" for more information.
You can extract substrings from the beginning or end of a string to a particular index, or from a specific range, with the substringToIndex:, substringFromIndex:, and substringWithRange: methods. You can also split a string into substrings (based on a separator string) with the componentsSeparatedByString: method.
Most of the NSString classes' remaining methods are for conveniences such as changing case, quickly extracting numeric values, and working with encodings. There's also a set of methods for treating strings as file system paths, described below in "Manipulating Paths" . An additional class cluster, NSScanner, allows you to scan a string object for numeric and string values. Both the NSString and the NSScanner class clusters use the NSCharacterSet class cluster for search operations. See the appropriate class specifications for more information.
In addition to all the basic methods for working with character strings merely as strings, NSString also provides a rich set of methods for manipulating strings as file system paths. A string can extract a path's directory, file name, and extension, expand a tilde expression (such as "~me") or create one for the user's home directory, and clean up paths containing symbolic links, redundant slashes, and references to "." (current directory) and ".." (parent directory). These methods are listed under "Working with paths" in the Method Types section.
NSString represents paths generically with '/
'
as the path separator and '.
'
as the extension separator. Methods that accept strings as path
arguments convert these generic representations to the proper system-specific
form as needed. On systems with an implicit root directory, absolute
paths begin with a path separator or with a tilde expression ("~/...
"
or "~user/...
").
The following constants are provided by NSStringReference:
Constant | Type | Description |
NSASCIIStringEncoding |
int | ASCII values 0..127 only |
NSISO2022JPStringEncoding |
int | ISO 2022 Japanese encoding for e-mail |
NSISOLatin1StringEncoding |
int | 5 |
NSISOLatin2StringEncoding |
int | 9 |
NSJapaneseEUCStringEncoding |
int | 3 |
NSMacOSRomanStringEncoding |
int | 30 |
NSNEXTSTEPStringEncoding |
int | 2 |
NSNonLossyASCIIStringEncoding |
int | 7 |
NSShiftJISStringEncoding |
int | 8 |
NSSymbolStringEncoding |
int | 6 |
NSUTF8StringEncoding |
int | 4 |
NSUnicodeStringEncoding |
int | 10 |
NSWindowsCP1250StringEncoding |
int | WinLatin2 |
NSWindowsCP1251StringEncoding |
int | Cyrillic; same as AdobeStandardCyrillic |
NSWindowsCP1252StringEncoding |
int | WinLatin1 |
NSWindowsCP1253StringEncoding |
int | Greek |
NSWindowsCP1254StringEncoding |
int | Turkish |
NSProprietaryStringEncoding |
int | Installation-specific encoding. |
NSCoding
- - encodeWithCoder:
- - initWithCoder:
NSCopying
- - copyWithZone:
NSMutableCopying
- - mutableCopyWithZone:
- Creating temporary strings
- + stringWithCString:
- + stringWithCString:length:
- + stringWithFormat:
- + localizedStringWithFormat:
- + stringWithContentsOfFile:
- + stringWithContentsOfURL:
- + stringWithCharacters:length:
- + string
- + stringWithString:
- + stringWithUTF8String:
- Initializing newly allocated strings
- - initWithCharactersNoCopy:length:freeWhenDone:
- - initWithCharacters:length:
- - initWithCStringNoCopy:length:freeWhenDone:
- - initWithCString:length:
- - initWithCString:
- - initWithString:
- - initWithUTF8String:
- - initWithFormat:
- - initWithFormat:arguments:
- - initWithFormat:locale:
- - initWithFormat:locale:arguments:
- - initWithData:encoding:
- - initWithContentsOfFile:
- - initWithContentsOfURL:
- - init
- Getting a string's length
- - length
- Accessing characters
- - characterAtIndex:
- - getCharacters:
- - getCharacters:range:
- Combining strings
- - stringByAppendingFormat:
- - stringByAppendingString:
- Dividing strings
- - componentsSeparatedByString:
- - substringFromIndex:
- - substringWithRange:
- - substringToIndex:
- Finding characters and substrings
- - rangeOfCharacterFromSet:
- - rangeOfCharacterFromSet:options:
- - rangeOfCharacterFromSet:options:range:
- - rangeOfString:
- - rangeOfString:options:
- - rangeOfString:options:range:
- Determining line ranges
- - getLineStart:end:contentsEnd:forRange:
- - lineRangeForRange:
- Determining composed character sequences
- - rangeOfComposedCharacterSequenceAtIndex:
- Converting string contents into a property list
- - propertyList
- - propertyListFromStringsFileFormat
- Identifying and comparing strings
- - caseInsensitiveCompare:
- - compare:
- - compare:options:
- - compare:options:range:
- - compare:options:range:locale:
- - hasPrefix:
- - hasSuffix:
- - isEqualToString:
- - hash
- - localizedCompare:
- - localizedCaseInsensitiveCompare:
- Getting a shared prefix
- - commonPrefixWithString:options:
- Changing case
- - capitalizedString
- - lowercaseString
- - uppercaseString
- Getting C strings
- - cString
- - lossyCString
- - cStringLength
- - getCString:
- - getCString:maxLength:
- - getCString:maxLength:range:remainingRange:
- Getting numeric values
- - doubleValue
- - floatValue
- - intValue
- Working with encodings
- + availableStringEncodings
- + defaultCStringEncoding
- + localizedNameOfStringEncoding:
- - canBeConvertedToEncoding:
- - dataUsingEncoding:
- - dataUsingEncoding:allowLossyConversion:
- - description
- - fastestEncoding
- - smallestEncoding
- Working with paths
- + pathWithComponents:
- - pathComponents
- - completePathIntoString:caseSensitive:matchesIntoArray:filterTypes:
- - fileSystemRepresentation
- - getFileSystemRepresentation:maxLength:
- - isAbsolutePath
- - lastPathComponent
- - pathExtension
- - stringByAbbreviatingWithTildeInPath
- - stringByAppendingPathComponent:
- - stringByAppendingPathExtension:
- - stringByDeletingLastPathComponent
- - stringByDeletingPathExtension
- - stringByExpandingTildeInPath
- - stringByResolvingSymlinksInPath
- - stringByStandardizingPath
- - stringsByAppendingPaths:
- Writing to a file
- - writeToFile:atomically:
- Writing to an URL
- - writeToURL
+ (const NSStringEncoding *)availableStringEncodings
NSASCIIStringEncoding
NSNEXTSTEPStringEncoding
NSUnicodeStringEncoding
NSISOLatin1StringEncoding
NSISOLatin2StringEncoding
NSSymbolStringEncoding
See the "Types and Constants" section of the Foundation Kit documentation for a complete list and descriptions of supported encodings.
See Also: + localizedNameOfStringEncoding:
+ (NSStringEncoding)defaultCStringEncoding
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
+ (NSString *)localizedStringWithFormat:(NSString
*)format,
...
NSString *myString = [NSString localizedStringWithFormat:@"%@: %d\n",@"Cost", 32];
The
resulting string has the value "Cost: 32\n
".
See "Creating and Converting String Objects" in the class cluster description for more information.
+ (NSString *)pathWithComponents:(NSArray
*)components
/
" as the first
component. To include a trailing path divider, use an empty string
as the last component. This method doesn't clean up the path created;
use stringByStandardizingPath to resolve
empty components, references to the parent directory, and so on.See Also: - pathComponents
+ (id)string
See Also: - init
+ (id)stringWithCharacters:(const
unichar *)chars
length:(unsigned)length
See Also: - initWithCharacters:length:
+ (id)stringWithContentsOfFile:(NSString
*)path
nil
if
the file can't be opened.See Also: - initWithContentsOfFile:, + defaultCStringEncoding
+ (id)stringWithContentsOfURL:(NSURL
*)anURL
See Also: - initWithContentsOfURL:, + defaultCStringEncoding
+ (id)stringWithCString:(const
char *)cString
See Also: - initWithCString:, + defaultCStringEncoding
+ (id)stringWithCString:(const
char *)cString
length:(unsigned)length
sizeof(char)
bytes
from cString, and doesn't stop
short at a zero character.See Also: - initWithCString:length:, + defaultCStringEncoding
+ (id)stringWithFormat:(NSString
*)format,
...
See Also: - initWithFormat:
+ (id)stringWithString:(NSString
*)aString
See Also: - initWithString:
+ (id)stringWithUTF8String:(const
char *)bytes
See Also: - initWithString:
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
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.
See Also: - dataUsingEncoding:allowLossyConversion:
- (NSString *)capitalizedString
Case transformations aren't guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercaseString for an example.
See Also: - lowercaseString, - uppercaseString
- (NSComparisonResult)caseInsensitiveCompare:(NSString
*)aString
NSCaseInsensitiveSearch
as
the only option.- (unichar)characterAtIndex:(unsigned)index
See Also: - getCharacters:, - getCharacters:range:
- (NSString *)commonPrefixWithString:(NSString
*)aString
options:(unsigned)mask
NSCaseInsensitiveSearch
NSLiteralSearch
See "Working with String Objects" in the class cluster description for details on these options.
See Also: - hasPrefix:
- (NSComparisonResult)compare:(NSString
*)aString
See Also: - compare:options:range:, - caseInsensitiveCompare:, - isEqualToString:
- (NSComparisonResult)compare:(NSString
*)aString
options:(unsigned)mask
See Also: - caseInsensitiveCompare:, - isEqualToString:
- (NSComparisonResult)compare:(NSString
*)aString
options:(unsigned)mask
range:(NSRange)aRange
NSOrderedAscending
if
the substring of the receiver given by aRange precedes aString in lexical
ordering, NSOrderedSame
if the substring
of the receiver and aString are equivalent
in lexical value, and NSOrderedDescending
if
the substring of the receiver follows aString. You
can specify the following options in mask by
combining them with the C bitwise OR operator:NSCaseInsensitiveSearch
NSLiteralSearch
See "Working with String Objects" in the class cluster description for details on these options.
Raises an NSRangeException if any part of aRange lies beyond the end of the string.
See Also: - caseInsensitiveCompare:, - isEqualToString:
- (NSComparisonResult)compare:(NSString
*)string
options:(unsigned)mask
range:(NSRange)compareRange
locale:(NSDictionary *)dict
- (unsigned)completePathIntoString:(NSString
**)outputName
caseSensitive:(BOOL)flag
matchesIntoArray:(NSArray **)outputArray
filterTypes:(NSArray *)filterTypes
Returns 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 nil. Hence, you can check for the existence of matches without retrieving by passing nil as outputArray
- (NSArray *)componentsSeparatedByString:(NSString
*)separator
NSString *list = @"wrenches, hammers, saws"; NSArray *listItems = [list componentsSeparatedByString:@", "];
produces an array with these contents:
Index | Substring |
0 | wrenches |
1 | hammers |
2 | saws |
If list begins with a comma and space-for example, ", wrenches, hammers, saws"-the array has these contents:
Index | Substring |
0 | (empty string) |
1 | wrenches |
2 | hammers |
3 | saws |
If list has no separators-for example, "wrenches"-the array contains the string itself, in this case "wrenches".
See Also: - componentsJoinedByString: (NSArray), - pathComponents
- (const char *)cString
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - getCString:, - canBeConvertedToEncoding:, + defaultCStringEncoding, - cStringLength, - getCharacters:
- (unsigned)cStringLength
Raises if the receiver
can't be represented in the default C string encoding without
loss of information. You can also use canBeConvertedToEncoding: to check
whether a string can be losslessly converted to the default C string
encoding. If it can't, use lossyCString to get a C string representation
with some loss of information, then check its length explicitly
using the ANSI function strlen()
.
See Also: - cString, - canBeConvertedToEncoding:, + defaultCStringEncoding, - length
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
allowLossyConversion:(BOOL)flag
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.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.
See Also: - canBeConvertedToEncoding:
- (NSString *)description
- (double)doubleValue
double
,
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 default locale; use an NSScanner for localized scanning of numeric values from a string.
See Also: - intValue, - floatValue, scanDouble: (NSScanner)
- (NSStringEncoding)fastestEncoding
See Also: - smallestEncoding, - getCharacters:range:
- (const char *)fileSystemRepresentation
Raises an NSCharacterConversionException if the receiver can't be represented in the file system's encoding.
- (float)floatValue
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 default locale; use an NSScanner for localized scanning of numeric values from a string.
See Also: - doubleValue, - intValue, scanFloat: (NSScanner)
- (void)getCharacters:(unichar
*)buffer
See Also: length
- (void)getCharacters:(unichar
*)buffer
range:(NSRange)aRange
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.
- (void)getCString:(char
*)buffer
NSMaximumStringLength
as
the maximum length, the receiver's entire extent as the range,
and nil for the remaining range. buffer must
be large enough to contain the resulting C string plus a terminating
zero character (which this method adds).Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - cStringLength, - canBeConvertedToEncoding:, + defaultCStringEncoding, - getCharacters:
- (void)getCString:(char
*)buffer
maxLength:(unsigned)maxLength
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - cStringLength, - canBeConvertedToEncoding:, + defaultCStringEncoding, - getCharacters:
- (void)getCString:(char
*)buffer
maxLength:(unsigned)maxLength
range:(NSRange)aRange
remainingRange:(NSRange *)leftoverRange
Raises an NSCharacterConversionException if the receiver can't be represented in the default C string encoding without loss of information. Use canBeConvertedToEncoding: if necessary to check whether a string can be losslessly converted to the default C string encoding. If it can't, use lossyCString or dataUsingEncoding:allowLossyConversion: to get a C string representation with some loss of information.
See Also: - cStringLength, - canBeConvertedToEncoding:, + defaultCStringEncoding, - getCharacters:
- (BOOL)getFileSystemRepresentation:(char
*)buffer
maxLength:(unsigned)maxLength
/
'
and '.
' respectively)
with their equivalents for the operating system.buffer must be large enough to contain maxLength chars plus a terminating zero char (which this method adds). Returns YES if buffer is successfully filled with a file system representation, NO if not (for example, if maxLength would be exceeded). Also returns NO if the receiver can't be represented in the file system's encoding.
If the system-specific path or extension separator appear in the abstract representation, the characters they're converted to depend on the system (unless they're identical to the abstract separators).
See Also: - fileSystemRepresentation
+ (void)getLineStart:(unsigned
*)startIndex
end:(unsigned *)lineEndIndex
contentsEnd:(unsigned *)contentsEndIndex
forRange:(NSRange)aRange
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)When this method returns, startIndex contains the index of the first character of the line, which is at or before the location of aRange; lineEndIndex contains the index of the first character past the line terminator; and contentsEndIndex contains the index of the first character of the line terminator itself. You may pass a nil pointer for any of these arguments, in which case the work to compute the value isn't performed.
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.
See Also: - lineRangeForRange:, - substringWithRange:
- (unsigned)hash
- (BOOL)hasPrefix:(NSString
*)aString
NSAnchoredSearch
option.
See "Working with String Objects" in the class cluster description
for more information.See Also: - hasSuffix:, - compare:options:range:
- (BOOL)hasSuffix:(NSString
*)aString
NSAnchoredSearch
and NSBackwardsSearch
options.
See "Working with String Objects" in the class cluster description
for more information.See Also: - hasPrefix:, - compare:options:range:
- (id)init
See Also: + string
- (id)initWithCharacters:(const
unichar *)characters
length:(unsigned)length
See Also: + stringWithCharacters:length:
- (id)initWithCharactersNoCopy:(unichar
*)characters
length:(unsigned)length
freeWhenDone:(BOOL)flag
See Also: + stringWithCharacters:length:
- (id)initWithContentsOfFile:(NSString
*)path
See Also: + stringWithContentsOfFile:, + defaultCStringEncoding
- (id)initWithContentsOfURL:(NSURL
*)anURL
See Also: + stringWithContentsOfURL:, + defaultCStringEncoding
- (id)initWithCString:(const
char *)cString
To create an immutable string from an immutable CString buffer, do not attempt to use this method. Instead, use initWithCStringNoCopy:length:freeWhenDone:.
See Also: + stringWithCString:, - initWithCStringNoCopy:length:freeWhenDone:, + defaultCStringEncoding
- (id)initWithCString:(const
char *)cString
length:(unsigned)length
sizeof(char)
bytes
from cString, and doesn't stop
short at a zero character. cString must
contain bytes in the default C string encoding, and may not be nil.
Returns self.See Also: + stringWithCString:length:, + defaultCStringEncoding
- (id)initWithCStringNoCopy:(char
*)cString
length:(unsigned)length
freeWhenDone:(BOOL)flag
sizeof(char)
bytes
from cString, and doesn't stop
short at a zero character. cString must
contain characters in the default C string encoding, and may not
be nil. The receiver becomes the owner of cString;
if flag is YES it will free the memory
when it no longer needs it, but if flag is NO it
won't. Returns self.You can use this method to create an immutable string from an immutable (const char*) C-string buffer. If you receive a warning message, you can disregard it; its purpose is simply to warn you that the C string passed as the method's first argument may be modified. If you make certain the freeWhenDone argument to initWithStringNoCopy is NO, the C string passed as the method's first argument cannot be modified, so you can safely use initWithStringNoCopy to create an immutable string from an immutable (const char*) C-string buffer.
See Also: + stringWithCString:length:, + defaultCStringEncoding
- (id)initWithData:(NSData
*)data
encoding:(NSStringEncoding)encoding
- (id)initWithFormat:(NSString
*)format,
...
See Also: + stringWithFormat:
- (id)initWithFormat:(NSString
*)format
arguments:(va_list)argList
nil
as
the locale.See Also: + stringWithFormat:
- (id)initWithFormat:(NSString
*)format
locale:(NSDictionary *)dictionary,
...
See Also: + localizedStringWithFormat:
- (id)initWithFormat:(NSString
*)format
locale:(NSDictionary *)dictionary
arguments:(va_list)argList
va_list myArgs; NSDictionary *myLocale; /* Assume this exists. */ NSString *myString = [[NSString alloc] initWithFormat:@"%@: %d\n", locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] arguments:myArgs];
(Note the message construct for retrieving the user's locale.). The resulting string has the value "Cost: 32\n".
See "Creating and Converting String Objects" in the class cluster description for more information. Returns self.
See Also: - initWithFormat:arguments:
- (id)initWithString:(NSString
*)aString
See Also: + stringWithString:
- (id)initWithUTF8String:(const
char *)bytes
See Also: + stringWithUTF8String:
- (int)intValue
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 default locale; use an NSScanner for localized scanning of numeric values from a string.
See Also: - doubleValue, - floatValue, scanInt: (NSScanner)
- (BOOL)isAbsolutePath
- (BOOL)isEqualToString:(NSString
*)aString
NSOrderedSame
), NO otherwise. When
you know both objects are strings, this method is a faster way to check
equality than isEqual:.See Also: - compare:options:range:
- (NSString *)lastPathComponent
Receiver's String Value | String Returned |
"/tmp/scratch.tiff " |
"scratch.tiff " |
"/tmp/scratch " |
"scratch " |
"/tmp/ " |
"tmp " |
"scratch " |
"scratch " |
"/ " |
"" (an empty string) |
- (unsigned int)length
See Also: - cStringLength, - sizeWithAttributes: (NSString Additions in the Application Kit)
+ (NSRange)lineRangeForRange:(NSRange)aRange
See Also: - getLineStart:end:contentsEnd:forRange:, - substringWithRange:
- (NSComparisonResult)localizedCompare:(NSString
*)string
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString
*)string
- (const char *)lossyCString
See Also: - getCString:, - canBeConvertedToEncoding:, + defaultCStringEncoding, - cStringLength, - getCharacters:
- (NSString *)lowercaseString
lcString = [myString lowercaseString];
might not be equal to this:
lcString = [[myString uppercaseString] lowercaseString];
For example, the uppercase form of "ß" in German is "SS", so converting "eßen" to uppercase then lowercase produces this sequence of strings:
See Also: - capitalizedString, - uppercaseString
- (NSArray *)pathComponents
NSString *path = @"tmp/scratch"; NSArray *pathComponents = [path componentsSeparatedByString:@"/"];
produces an array with these contents:
Index | Path Component |
0 | "tmp " |
1 | "scratch " |
If the receiver begins with a slash-for example,
"/tmp/scratch
"-the
array has these contents:
Index | Path Component |
0 | "/ " |
1 | "tmp " |
2 | "scratch " |
If the receiver has no separators-for example, "scratch
"-the
array contains the string itself, in this case "scratch
".
See Also: + pathWithComponents:, - stringByStandardizingPath, - componentsSeparatedByString:
- (NSString *)pathExtension
Receiver's String Value | String Returned |
"/tmp/scratch.tiff " |
"tiff " |
"/tmp/scratch " |
"" (an empty string) |
"/tmp/ " |
"" (an empty string) |
"/tmp/scratch..tiff " |
"tiff " |
- (id)propertyList
In a well formed property list, arrays are delimited by parentheses, with individual elements separated by commas and optional spaces. Dictionaries are delimited by curly braces, with key-value pairs separated by semicolons, the key and value separated by an equals sign. Strings appear as plain text if they contain no whitespace, or enclosed in straight quotation marks if they do. Data items are delimited by angle brackets and encoded as hexadecimal digits. Here's a short example of a text-format property list:
{ Title = "Star Wars"; Director = "Lucas, George"; Cast = ( "Hamill, Mark", "Fisher, Carrie", "Ford, Harrison" ); "Thumbnail Image" = <040b7479 70656473 (many more sets of digits) 8484074e>; }
See Also: - propertyListFromStringsFileFormat, + stringWithContentsOfFile:
- (NSDictionary *)propertyListFromStringsFileFormat
/*
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";
See Also: - propertyList, + stringWithContentsOfFile:
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet
*)aSet
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet
*)aSet
options:(unsigned int)mask
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet
*)aSet
options:(unsigned int)mask
range:(NSRange)aRange
NSCaseInsensitiveSearch
NSLiteralSearch
NSBackwardsSearch
See "Working with String Objects" in the class cluster description for details on these options. Raises an NSRangeException if any part of aRange lies beyond the end of the string.
Because precomposed characters in aSet can match composed characters sequences in the receiver, the length of the returned range can be greater than one. For example, if you search for "ü" in the string "stru¨del", the returned range is {3,2}.
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(unsigned)anIndex
Raises an NSRangeException if anIndex lies beyond the end of the string.
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 this:
- (NSRange)adjustRange:(NSRange)aRange { unsigned int index, endIndex; NSRange newRange, endRange; index = aRange.location; newRange = [self rangeOfComposedCharacterSequenceAtIndex:index]; index = aRange.location + aRange.length; endRange = [self rangeOfComposedCharacterSequenceAtIndex:index]; endIndex = endRange.location + endRange.length; newRange.length = endIndex - newRange.location; return newRange; }
adjustRange: begins by correcting 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.
- (NSRange)rangeOfString:(NSString
*)aString
- (NSRange)rangeOfString:(NSString
*)aString
options:(unsigned)mask
- (NSRange)rangeOfString:(NSString
*)subString
options:(unsigned)mask
range:(NSRange)aRange
NSCaseInsensitiveSearch
NSLiteralSearch
NSBackwardsSearch
NSAnchoredSearch
See "Working with String Objects" in the class cluster description for details on these options. Raises an NSRangeException if any part of aRange lies beyond the end of the string. Returns a range of {NSNotFound, 0} if subString is the null string.
- (NSStringEncoding)smallestEncoding
See Also: - fastestEncoding, - getCharacters:range:
- (NSString *)stringByAbbreviatingWithTildeInPath
~
",
substituted for the full path to the current user's home directory,
or "~user
" for a
user other than the current user. Returns the receiver
unaltered if it doesn't begin with the user's home directory.See Also: - stringByExpandingTildeInPath
- (NSString *)stringByAppendingFormat:(NSString
*)format,
...
See Also: - stringByAppendingString:
- (NSString *)stringByAppendingPathComponent:(NSString
*)aString
scratch.tiff
":Receiver's String Value | Resulting String |
"/tmp " |
"/tmp/scratch.tiff " |
"/tmp/ " |
"/tmp/scratch.tiff " |
"/ " |
"/scratch.tiff " |
"" (an empty string) | "scratch.tiff " |
See Also: - stringsByAppendingPaths:, - stringByAppendingPathExtension:, - stringByDeletingLastPathComponent
- (NSString *)stringByAppendingPathExtension:(NSString
*)string
@"tiff"
:Receiver's String Value | Resulting String |
"/tmp/scratch.old " |
"/tmp/scratch.old.tiff " |
"/tmp/scratch. " |
"/tmp/scratch..tiff " |
"/tmp/ " |
"/tmp/.tiff " |
"scratch " |
"scratch.tiff " |
See Also: - stringByAppendingPathComponent:, - stringByDeletingPathExtension
- (NSString *)stringByAppendingString:(NSString
*)aString
NSString *errorTag = @"Error: "; NSString *errorString = @"premature end of file."; NSString *errorMessage = [errorTag stringByAppendingString:errorString];
produces
the string "Error: premature end of file.
".
See Also: - stringByAppendingFormat:
- (NSString *)stringByDeletingLastPathComponent
Receiver's String Value | Resulting String |
"/tmp/scratch.tiff " |
"/tmp " |
"/tmp/lock/ " |
"/tmp " |
"/tmp/ " |
"/ " |
"/tmp " |
"/ " |
"/ " |
"/ " |
"scratch.tiff " |
"" (an empty string) |
See Also: - stringByDeletingPathExtension, - stringByAppendingPathComponent:
- (NSString *)stringByDeletingPathExtension
Receiver's String Value | Resulting String |
"/tmp/scratch.tiff " |
"/tmp/scratch " |
"/tmp/ " |
"/tmp " |
"scratch.bundle/ " |
"scratch " |
"scratch..tiff " |
"scratch. " |
".tiff " |
"" (an empty string) |
"/ " |
"/ " |
See Also: - pathExtension, - stringByDeletingLastPathComponent
- (NSString *)stringByExpandingTildeInPath
~
"
or "~user
", to its full
path value. Returns the receiver unaltered if
that component can't be expanded.See Also: - stringByAbbreviatingWithTildeInPath
- (NSString *)stringByResolvingSymlinksInPath
Expands an initial tilde expression in the receiving path, then resolves all symbolic links and references to current or parent directories if possible, returning 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.
See Also: - stringByStandardizingPath, - stringByExpandingTildeInPath
- (NSString *)stringByStandardizingPath
This method can make the following changes in the provided string:
/private
"
from the path if the result still indicates an existing file or
directory (checked by consulting the file system).See Also: - stringByExpandingTildeInPath, - stringByResolvingSymlinksInPath
- (NSArray *)stringsByAppendingPaths:(NSArray
*)paths
- (NSString *)substringFromIndex:(unsigned)anIndex
See Also: - substringWithRange:, - substringToIndex:
- (NSString *)substringToIndex:(unsigned)anIndex
See Also: - substringFromIndex:, - substringWithRange:
- (NSString *)substringWithRange:(NSRange)aRange
See Also: - substringFromIndex:, - substringToIndex:
- (NSString *)uppercaseString
See Also: - capitalizedString, - lowercaseString
- (const char *)UTF8String
- (BOOL)writeToFile:(NSString
*)path
atomically:(BOOL)flag
If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.
See Also: + defaultCStringEncoding
- (BOOL)writeToURL:(NSURL
*)anURL
atomically:(BOOL)atomically
atomically is ignored if anURL is not of a type that can be accessed atomically.
See Also: + defaultCStringEncoding