struct String
Inheritance |
Comparable, CustomDebugStringConvertible, Equatable, ExtendedGraphemeClusterLiteralConvertible, Hashable, MirrorPathType, OutputStreamType, Streamable, StringInterpolationConvertible, StringLiteralConvertible, UnicodeScalarLiteralConvertible, _ObjectiveCBridgeable, _Reflectable
View Protocol Hierarchy →
|
---|---|
Associated Types | |
Nested Types | String.CharacterView, String.UnicodeScalarView, String.UTF16View, String.UTF8View, String.CharacterView.Index, String.UnicodeScalarView.Index, String.UnicodeScalarView.Generator, String.UTF16View.Index, String.UTF8View.Index |
Import | import Swift |
Initializers
Construct an instance containing just the given Character
.
Declaration
init(_ c: Character)
Construct the String
corresponding to the given sequence of
Unicode scalars.
Declaration
init(_ characters: String.CharacterView)
Construct the String
corresponding to the given sequence of
Unicode scalars.
Declaration
init(_ unicodeScalars: String.UnicodeScalarView)
Initialize self
with the textual representation of instance
.
- If
T
conforms toStreamable
, the result is obtained by callinginstance.writeTo(s)
on an empty string s. - Otherwise, if
T
conforms toCustomStringConvertible
, the result isinstance
'sdescription
- Otherwise, if
T
conforms toCustomDebugStringConvertible
, the result isinstance
'sdebugDescription
- Otherwise, an unspecified result is supplied automatically by the Swift standard library.
See Also: String.init<T>(reflecting: T)
Declaration
init<T>(_ instance: T)
Create an instance representing v
in base 10.
Declaration
init<T : _SignedIntegerType>(_ v: T)
Create an instance representing v
in base 10.
Declaration
init<T : UnsignedIntegerType>(_ v: T)
Create an instance containing characters
.
Declaration
init<S : SequenceType where S.Generator.Element == Character>(_ characters: S)
Create an instance representing v
in the given radix
(base).
Numerals greater than 9 are represented as roman letters,
starting with a
if uppercase
is false
or A
otherwise.
Declaration
init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
Create an instance representing v
in the given radix
(base).
Numerals greater than 9 are represented as roman letters,
starting with a
if uppercase
is false
or A
otherwise.
Declaration
init<T : UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
Declaration
init(_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1)
Declaration
init(_builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1)
Declaration
init(_builtinUTF16StringLiteral start: Builtin.RawPointer, numberOfCodeUnits: Builtin.Word)
Declaration
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
[Foundation] Produces a string created by reading data from the file at a given path interpreted using a given encoding.
Declaration
init(contentsOfFile path: String, encoding enc: NSStringEncoding)
[Foundation] Produces a string created by reading data from the file at a given path and returns by reference the encoding used to interpret the file.
Declaration
init(contentsOfFile path: String, usedEncoding: UnsafeMutablePointer<NSStringEncoding> = default)
[Foundation] Produces a string created by reading data from a given URL
interpreted using a given encoding. Errors are written into the
inout error
argument.
Declaration
init(contentsOfURL url: NSURL, encoding enc: NSStringEncoding)
[Foundation] Produces a string created by reading data from a given URL
and returns by reference the encoding used to interpret the
data. Errors are written into the inout error
argument.
Declaration
init(contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<NSStringEncoding> = default)
Construct an instance that is the concatenation of count
copies
of repeatedValue
.
Declaration
init(count: Int, repeatedValue c: Character)
Construct an instance that is the concatenation of count
copies
of Character(repeatedValue)
.
Declaration
init(count: Int, repeatedValue c: UnicodeScalar)
Create an instance initialized to value
.
Declaration
init(extendedGraphemeClusterLiteral value: String)
[Foundation] Returns a String
object initialized by using a given
format string as a template into which the remaining argument
values are substituted.
Declaration
init(format: String, _ arguments: CVarArgType...)
[Foundation] Returns a String
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.
Declaration
init(format: String, arguments: [CVarArgType])
[Foundation] Returns a String
object initialized by using a given
format string as a template into which the remaining argument
values are substituted according to given locale information.
Declaration
init(format: String, locale: NSLocale?, _ args: CVarArgType...)
[Foundation] Returns a String
object initialized by using a given
format string as a template into which the remaining argument
values are substituted according to given locale information.
Declaration
init(format: String, locale: NSLocale?, arguments: [CVarArgType])
Initialize self
with a detailed textual representation of
subject
, suitable for debugging.
If
T
conforms toCustomDebugStringConvertible
, the result issubject
'sdebugDescription
.Otherwise, if
T
conforms toCustomStringConvertible
, the result issubject
'sdescription
.Otherwise, if
T
conforms toStreamable
, the result is obtained by callingsubject.writeTo(s)
on an empty string s.Otherwise, an unspecified result is supplied automatically by the Swift standard library.
See Also: String.init<T>(T)
Declaration
init<T>(reflecting subject: T)
Create an instance by concatenating the elements of strings
.
Declaration
init(stringInterpolation strings: String...)
Declaration
init(stringInterpolationSegment expr: Character)
Declaration
init(stringInterpolationSegment expr: Float32)
Declaration
init(stringInterpolationSegment expr: Float64)
Declaration
init(stringInterpolationSegment expr: UnicodeScalar)
Create an instance containing expr
's print
representation.
Declaration
init<T>(stringInterpolationSegment expr: T)
Create an instance initialized to value
.
Declaration
init(stringLiteral value: String)
Create an instance initialized to value
.
Declaration
init(unicodeScalarLiteral value: String)
[Foundation] Returns an initialized String
object that contains a
given number of characters from a given array of Unicode
characters.
Declaration
init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)
[Foundation] Returns an initialized String
object that contains a given
number of characters from a given array of UTF-16 Code Units
Declaration
init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool)
Construct the String
corresponding to the given sequence of
UTF-8 code units. If utf8
contains unpaired surrogates, the
result is nil
.
Declaration
init?(_ utf8: String.UTF8View)
Construct the String
corresponding to the given sequence of
UTF-16 code units. If utf16
contains unpaired surrogates, the
result is nil
.
Declaration
init?(_ utf16: String.UTF16View)
[Foundation] Produces a string containing the bytes in a given C array, interpreted according to a given encoding.
Declaration
init?(CString: UnsafePointer<CChar>, encoding enc: NSStringEncoding)
[Foundation] Produces a string created by copying the data from a given C array of UTF8-encoded bytes.
Declaration
init?(UTF8String bytes: UnsafePointer<CChar>)
[Foundation] Produces an initialized NSString
object equivalent to the given
bytes
interpreted in the given encoding
.
Declaration
init?<S : SequenceType where S.Generator.Element == UInt8>(bytes: S, encoding: NSStringEncoding)
[Foundation] Produces an initialized String
object that contains a
given number of bytes from a given buffer of bytes interpreted
in a given encoding, and optionally frees the buffer. WARNING:
this initializer is not memory-safe!
Declaration
init?(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, encoding: NSStringEncoding, freeWhenDone flag: Bool)
[Foundation] Returns a String
initialized by converting given data
into
Unicode characters using a given encoding
.
Declaration
init?(data: NSData, encoding: NSStringEncoding)
Instance Variables
[Foundation] Produce a string with the first character from each word changed to the corresponding uppercase value.
Declaration
var capitalizedString: String { get }
A collection of Characters
representing the String
's
extended grapheme
clusters.
Declaration
var characters: String.CharacterView { get }
A textual representation of self
, suitable for debugging.
Declaration
var debugDescription: String { get }
[Foundation] Returns a string made by normalizing the String
’s
contents using Form D.
Declaration
var decomposedStringWithCanonicalMapping: String { get }
[Foundation] Returns a string made by normalizing the String
’s
contents using Form KD.
Declaration
var decomposedStringWithCompatibilityMapping: String { get }
The "past the end" position in self.characters
.
endIndex
is not a valid argument to subscript
, and is always
reachable from startIndex
by zero or more applications of
successor()
.
Declaration
var endIndex: Index { get }
[Foundation] Returns the fastest encoding to which the String
may be
converted without loss of information.
Declaration
var fastestEncoding: NSStringEncoding { get }
[Foundation] An unsigned integer that can be used as a hash table address.
Declaration
var hash: Int { get }
The hash value.
Axiom: x == y
implies x.hashValue == y.hashValue
.
Note: The hash value is not guaranteed to be stable across different invocations of the same program. Do not persist the hash value across program runs.
Declaration
var hashValue: Int { get }
[Foundation] A capitalized representation of the String
that is produced
using the current locale.
Declaration
var localizedCapitalizedString: String { get }
[Foundation] A lowercase version of the string that is produced using the current locale.
Declaration
var localizedLowercaseString: String { get }
[Foundation] An uppercase version of the string that is produced using the current locale.
Declaration
var localizedUppercaseString: String { get }
A contiguously-stored nul-terminated UTF-8 representation of
self
.
To access the underlying memory, invoke
withUnsafeBufferPointer
on the ContiguousArray
.
Declaration
var nulTerminatedUTF8: ContiguousArray<CodeUnit> { get }
[Foundation] Returns a string made by normalizing the String
’s
contents using Form C.
Declaration
var precomposedStringWithCanonicalMapping: String { get }
[Foundation] Returns a string made by normalizing the String
’s
contents using Form KC.
Declaration
var precomposedStringWithCompatibilityMapping: String { get }
[Foundation] Returns the smallest encoding to which the String
can
be converted without loss of information.
Declaration
var smallestEncoding: NSStringEncoding { get }
The position of the first Character
in self.characters
if
self
is non-empty; identical to endIndex
otherwise.
Declaration
var startIndex: Index { get }
[Foundation] Returns a new string made from the String
by replacing
all percent encoded sequences with the matching UTF-8
characters.
Declaration
var stringByRemovingPercentEncoding: String? { get }
The value of self
as a collection of Unicode scalar values.
Declaration
var unicodeScalars: String.UnicodeScalarView { get set }
A UTF-16 encoding of self
.
Declaration
var utf16: String.UTF16View { get }
Subscripts
Access the Character
at position
.
Requires: position
is a valid position in self.characters
and position != endIndex
.
Declaration
subscript(i: Index) -> Character { get }
Access the characters in the given subRange
.
Complexity: O(1) unless bridging from Objective-C requires an O(N) conversion.
Declaration
subscript(subRange: Range<Index>) -> String { get }
Static Methods
[Foundation] Returns an Array of the encodings string objects support in the application’s environment.
Declaration
static func availableStringEncodings() -> [NSStringEncoding]
[Foundation] Returns the C-string encoding assumed for any method accepting a C string as an argument.
Declaration
static func defaultCStringEncoding() -> NSStringEncoding
Creates a new String
by copying the nul-terminated UTF-8 data
referenced by a CString
.
Returns nil
if the CString
is NULL
or if it contains ill-formed
UTF-8 code unit sequences.
Declaration
static func fromCString(cs: UnsafePointer<CChar>) -> String?
Creates a new String
by copying the nul-terminated UTF-8 data
referenced by a CString
.
Returns nil
if the CString
is NULL
. If CString
contains
ill-formed UTF-8 code unit sequences, replaces them with replacement
characters (U+FFFD).
Declaration
static func fromCStringRepairingIllFormedUTF8(cs: UnsafePointer<CChar>) -> (String?, hadError: Bool)
Returns a human-readable string giving the name of a given encoding.
Declaration
static func localizedNameOfStringEncoding(encoding: NSStringEncoding) -> String
[Foundation] 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.
Declaration
static func localizedStringWithFormat(format: String, _ arguments: CVarArgType...) -> String
Instance Methods
Append x
to self
.
Complexity: Amortized O(1).
Declaration
mutating func append(x: UnicodeScalar)
Append the elements of other
to self
.
Declaration
mutating func appendContentsOf(other: String)
Declaration
mutating func appendContentsOf<S : SequenceType where S.Generator.Element == Character>(newElements: S)
[Foundation] Returns a representation of the String
as a C string
using a given encoding.
Declaration
func cStringUsingEncoding(encoding: NSStringEncoding) -> [CChar]?
[Foundation] Returns a Boolean value that indicates whether the
String
can be converted to a given encoding without loss of
information.
Declaration
func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool
[Foundation] Returns a capitalized representation of the String
using the specified locale.
Declaration
func capitalizedStringWithLocale(locale: NSLocale?) -> String
[Foundation] Returns the result of invoking compare:options:
with
NSCaseInsensitiveSearch
as the only option.
Declaration
func caseInsensitiveCompare(aString: String) -> NSComparisonResult
[Foundation] Returns a string containing characters the String
and a
given string have in common, starting from the beginning of each
up to the first characters that aren’t equivalent.
Declaration
func commonPrefixWithString(aString: String, options: NSStringCompareOptions) -> String
[Foundation] Compares the string using the specified options and returns the lexical ordering for the range.
Declaration
func compare(aString: String, options mask: NSStringCompareOptions = default, range: Range<Index>? = default, locale: NSLocale? = default) -> NSComparisonResult
[Foundation] Interprets the String
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 String
.
Returns the actual number of matching paths.
Declaration
func completePathIntoString(outputName: UnsafeMutablePointer<String> = default, caseSensitive: Bool, matchesIntoArray: UnsafeMutablePointer<[String]> = default, filterTypes: [String]? = default) -> Int
[Foundation] Returns an array containing substrings from the String
that have been divided by characters in a given set.
Declaration
func componentsSeparatedByCharactersInSet(separator: NSCharacterSet) -> [String]
[Foundation] Returns an array containing substrings from the String
that have been divided by a given separator.
Declaration
func componentsSeparatedByString(separator: String) -> [String]
[Foundation] Returns true
iff other
is non-empty and contained within
self
by case-sensitive, non-literal search.
Equivalent to self.rangeOfString(other) != nil
Declaration
func containsString(other: String) -> Bool
[Foundation] Returns an NSData
object containing a representation of
the String
encoded using a given encoding.
Declaration
func dataUsingEncoding(encoding: NSStringEncoding, allowLossyConversion: Bool = default) -> NSData?
[Foundation] Enumerates all the lines in a string.
Declaration
func enumerateLines(body: (line: String, inout stop: Bool) -> ())
[Foundation] Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags.
Declaration
func enumerateLinguisticTagsInRange(range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTaggerOptions, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> ())
[Foundation] Enumerates the substrings of the specified type in the specified range of the string.
Declaration
func enumerateSubstringsInRange(range: Range<Index>, options opts: NSStringEnumerationOptions, _ body: (substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool) -> ())
[Foundation] Writes the given range
of characters into buffer
in a given
encoding
, without any allocations. Does not NULL-terminate.
buffer
: A buffer into which to store the bytes from
the receiver. The returned bytes are not NUL-terminated.
maxBufferCount
: The maximum number of bytes to write
to buffer.
usedBufferCount
: The number of bytes used from
buffer. Pass nil
if you do not need this value.
encoding
: The encoding to use for the returned bytes.
options
: A mask to specify options to use for
converting the receiver’s contents to encoding
(if conversion
is necessary).
range
: The range of characters in the receiver to get.
leftover
: The remaining range. Pass nil
If you do
not need this value.
Returns: true
iff some characters were converted.
Note: Conversion stops when the buffer fills or when the conversion isn't possible due to the chosen encoding.
Note: will get a maximum of min(buffer.count, maxLength)
bytes.
Declaration
func getBytes(inout buffer: [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: NSStringEncoding, options: NSStringEncodingConversionOptions, range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>>) -> Bool
[Foundation] Converts the String
’s content to a given encoding and
stores them in a buffer.
Note: will store a maximum of min(buffer.count, maxLength)
bytes.
Declaration
func getCString(inout buffer: [CChar], maxLength: Int, encoding: NSStringEncoding) -> Bool
[Foundation] Returns by reference the beginning of the first line and the end of the last line touched by the given range.
Declaration
func getLineStart(start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index>)
[Foundation] Returns by reference the beginning of the first paragraph and the end of the last paragraph touched by the given range.
Declaration
func getParagraphStart(start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index>)
Returns true
iff self
begins with prefix
.
Declaration
func hasPrefix(prefix: String) -> Bool
Returns true
iff self
ends with suffix
.
Declaration
func hasSuffix(suffix: String) -> Bool
Insert newElement
at index i
.
Invalidates all indices with respect to self
.
Complexity: O(self.count
).
Declaration
mutating func insert(newElement: Character, atIndex i: Index)
Insert newElements
at index i
.
Invalidates all indices with respect to self
.
Complexity: O(self.count + newElements.count
).
Declaration
mutating func insertContentsOf<S : CollectionType where S.Generator.Element == Character>(newElements: S, at i: Index)
[Foundation] Returns the number of bytes required to store the
String
in a given encoding.
Declaration
func lengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int
[Foundation] Returns the range of characters representing the line or lines containing a given range.
Declaration
func lineRangeForRange(aRange: Range<Index>) -> Range<Index>
[Foundation] Returns an array of linguistic tags for the specified range and requested tags within the receiving string.
Declaration
func linguisticTagsInRange(range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTaggerOptions = default, orthography: NSOrthography? = default, tokenRanges: UnsafeMutablePointer<[Range<Index>]> = default) -> [String]
[Foundation] Compares the string and a given string using a case-insensitive, localized, comparison.
Declaration
func localizedCaseInsensitiveCompare(aString: String) -> NSComparisonResult
[Foundation] Returns true
iff other
is non-empty and contained within
self
by case-insensitive, non-literal search, taking into
account the current locale.
Locale-independent case-insensitive operation, and other needs,
can be achieved by calling
rangeOfString(_:options:,range:_locale:_)
.
Equivalent to
self.rangeOfString(
other, options: .CaseInsensitiveSearch,
locale: NSLocale.currentLocale()) != nil
Declaration
func localizedCaseInsensitiveContainsString(other: String) -> Bool
[Foundation] Compares the string and a given string using a localized comparison.
Declaration
func localizedCompare(aString: String) -> NSComparisonResult
[Foundation] Compares strings as sorted by the Finder.
Declaration
func localizedStandardCompare(string: String) -> NSComparisonResult
[Foundation] Returns true
if self
contains string
, taking the current locale
into account.
This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.
Declaration
func localizedStandardContainsString(string: String) -> Bool
[Foundation] Finds and returns the range of the first occurrence of a given string,
taking the current locale into account. Returns nil
if the string was
not found.
This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.
Declaration
func localizedStandardRangeOfString(string: String) -> Range<Index>?
[Foundation] Returns a version of the string with all letters converted to lowercase, taking into account the specified locale.
Declaration
func lowercaseStringWithLocale(locale: NSLocale?) -> String
[Foundation] Returns the maximum number of bytes needed to store the
String
in a given encoding.
Declaration
func maximumLengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int
[Foundation] Returns the range of characters representing the paragraph or paragraphs containing a given range.
Declaration
func paragraphRangeForRange(aRange: Range<Index>) -> Range<Index>
[Foundation] Parses the String
as a text representation of a
property list, returning an NSString, NSData, NSArray, or
NSDictionary object, according to the topmost element.
Declaration
func propertyList() -> AnyObject
[Foundation] Returns a dictionary object initialized with the keys and
values found in the String
.
Declaration
func propertyListFromStringsFileFormat() -> [String : String]
[Foundation] Finds and returns the range in the String
of the first
character from a given character set found in a given range with
given options.
Declaration
func rangeOfCharacterFromSet(aSet: NSCharacterSet, options mask: NSStringCompareOptions = default, range aRange: Range<Index>? = default) -> Range<Index>?
[Foundation] Returns the range in the String
of the composed
character sequence located at a given index.
Declaration
func rangeOfComposedCharacterSequenceAtIndex(anIndex: Index) -> Range<Index>
[Foundation] Returns the range in the string of the composed character sequences for a given range.
Declaration
func rangeOfComposedCharacterSequencesForRange(range: Range<Index>) -> Range<Index>
[Foundation] Finds and returns the range of the first occurrence of a
given string within a given range of the String
, subject to
given options, using the specified locale, if any.
Declaration
func rangeOfString(aString: String, options mask: NSStringCompareOptions = default, range searchRange: Range<Index>? = default, locale: NSLocale? = default) -> Range<Index>?
Remove all characters.
Invalidates all indices with respect to self
.
keepCapacity
: If true
, prevents the release of
allocated storage, which can be a useful optimization
when self
is going to be grown again.
Declaration
mutating func removeAll(keepCapacity keepCapacity: Bool = default)
Remove and return the element at index i
.
Invalidates all indices with respect to self
.
Complexity: O(self.count
).
Declaration
mutating func removeAtIndex(i: Index) -> Character
Remove the indicated subRange
of characters.
Invalidates all indices with respect to self
.
Complexity: O(self.count
).
Declaration
mutating func removeRange(subRange: Range<Index>)
Replace the given subRange
of elements with newElements
.
Invalidates all indices with respect to self
.
Complexity: O(subRange.count
) if subRange.endIndex
== self.endIndex
and newElements.isEmpty
, O(N) otherwise.
Declaration
mutating func replaceRange(subRange: Range<Index>, with newElements: String)
Replace the given subRange
of elements with newElements
.
Invalidates all indices with respect to self
.
Complexity: O(subRange.count
) if subRange.endIndex
== self.endIndex
and newElements.isEmpty
, O(N) otherwise.
Declaration
mutating func replaceRange<C : CollectionType where C.Generator.Element == Character>(subRange: Range<Index>, with newElements: C)
[Foundation] Returns a new string made from the String
by replacing
all characters not in the specified set with percent encoded
characters.
Declaration
func stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters: NSCharacterSet) -> String?
[Foundation] Returns a representation of the String
using a given
encoding to determine the percent escapes necessary to convert
the String
into a legal URL string.
Deprecated: Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid..
Declaration
func stringByAddingPercentEscapesUsingEncoding(encoding: NSStringEncoding) -> String?
[Foundation] Returns a string made by appending to the String
a
string constructed from a given format string and the following
arguments.
Declaration
func stringByAppendingFormat(format: String, _ arguments: CVarArgType...) -> String
[Foundation] Returns a new string made by appending a given string to
the String
.
Declaration
func stringByAppendingString(aString: String) -> String
[Foundation] Perform string transliteration.
Declaration
func stringByApplyingTransform(transform: String, reverse: Bool) -> String?
[Foundation] Returns a string with the given character folding options applied.
Declaration
func stringByFoldingWithOptions(options: NSStringCompareOptions, locale: NSLocale?) -> String
[Foundation] Returns a new string formed from the String
by either
removing characters from the end, or by appending as many
occurrences as necessary of a given pad string.
Declaration
func stringByPaddingToLength(newLength: Int, withString padString: String, startingAtIndex padIndex: Int) -> String
[Foundation] Returns a new string in which the characters in a
specified range of the String
are replaced by a given string.
Declaration
func stringByReplacingCharactersInRange(range: Range<Index>, withString replacement: String) -> String
[Foundation] Returns a new string in which all occurrences of a target
string in a specified range of the String
are replaced by
another given string.
Declaration
func stringByReplacingOccurrencesOfString(target: String, withString replacement: String, options: NSStringCompareOptions = default, range searchRange: Range<Index>? = default) -> String
[Foundation] Returns a new string made by replacing in the String
all percent escapes with the matching characters as determined
by a given encoding.
Deprecated: Use stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding..
Declaration
func stringByReplacingPercentEscapesUsingEncoding(encoding: NSStringEncoding) -> String?
[Foundation] Returns a new string made by removing from both ends of
the String
characters contained in a given character set.
Declaration
func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String
[Foundation] Returns a new string containing the characters of the
String
from the one at a given index to the end.
Declaration
func substringFromIndex(index: Index) -> String
[Foundation] Returns a new string containing the characters of the
String
up to, but not including, the one at a given index.
Declaration
func substringToIndex(index: Index) -> String
[Foundation] Returns a string object containing the characters of the
String
that lie within a given range.
Declaration
func substringWithRange(aRange: Range<Index>) -> String
[Foundation] Returns a version of the string with all letters converted to uppercase, taking into account the specified locale.
Declaration
func uppercaseStringWithLocale(locale: NSLocale?) -> String
Invoke f
on the contents of this string, represented as
a nul-terminated array of char, ensuring that the array's
lifetime extends through the execution of f
.
Declaration
func withCString<Result>(@noescape f: UnsafePointer<Int8> throws -> Result) rethrows -> Result
Efficiently mutate self
by applying body
to its characters
.
Warning: Do not rely on anything about self
(the String
that is the target of this method) during the execution of
body
: it may not appear to have its correct value. Instead,
use only the String.CharacterView
argument to body
.
Declaration
mutating func withMutableCharacters<R>(body: (inout String.CharacterView) -> R) -> R
Write a textual representation of self
into target
.
Declaration
func writeTo<Target : OutputStreamType>(inout target: Target)
[Foundation] Writes the contents of the String
to a file at a given
path using a given encoding.
Declaration
func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: NSStringEncoding) throws
[Foundation] Writes the contents of the String
to the URL specified
by url using the specified encoding.
Declaration
func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: NSStringEncoding) throws
An arbitrary Unicode string value.
Unicode-Correct
Swift strings are designed to be Unicode-correct. In particular, the APIs make it easy to write code that works correctly, and does not surprise end-users, regardless of where you venture in the Unicode character space. For example, the
==
operator checks for Unicode canonical equivalence, so two different representations of the same string will always compare equal.Locale-Insensitive
The fundamental operations on Swift strings are not sensitive to locale settings. That's because, for example, the validity of a
Dictionary<String, T>
in a running program depends on a given string comparison having a single, stable result. Therefore, Swift always uses the default, un-tailored Unicode algorithms for basic string operations.Importing
Foundation
endows swift strings with the full power of theNSString
API, which allows you to choose more complex locale-sensitive operations explicitly.Value Semantics
Each string variable,
let
binding, or stored property has an independent value, so mutations to the string are not observable through its copies:Strings use Copy-on-Write so that their data is only copied lazily, upon mutation, when more than one string instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost
O(N)
time and space, whereN
is the length of the string's (unspecified) underlying representation.Views
String
is not itself a collection of anything. Instead, it has properties that present the string's contents as meaningful collections:characters
: a collection ofCharacter
(extended grapheme cluster) elements, a unit of text that is meaningful to most humans.unicodeScalars
: a collection ofUnicodeScalar
(Unicode scalar values) the 21-bit codes that are the basic unit of Unicode. These values are equivalent to UTF-32 code units.utf16
: a collection ofUTF16.CodeUnit
, the 16-bit elements of the string's UTF-16 encoding.utf8
: a collection ofUTF8.CodeUnit
, the 8-bit elements of the string's UTF-8 encoding.Growth and Capacity
When a string's contiguous storage fills up, new storage must be allocated and characters must be moved to the new storage.
String
uses an exponential growth strategy that makesappend
a constant time operation when amortized over many invocations.Objective-C Bridge
String
is bridged to Objective-C asNSString
, and aString
that originated in Objective-C may store its characters in anNSString
. Since any arbitrary subclass ofNSString
can become aString
, there are no guarantees about representation or efficiency in this case. SinceNSString
is immutable, it is just as though the storage was shared by some copy: the first in any sequence of mutating operations causes elements to be copied into unique, contiguous storage which may costO(N)
time and space, whereN
is the length of the string representation (or more, if the underlyingNSString
has unusual performance characteristics).