String
8 methodsA Unicode string value that is a collection of characters. A value type bridged to NSString.
String.count -> IntThe number of characters (extended grapheme clusters) in the string.
Returns
Int
Example
let s = "Hello"
print(s.count) // 5
let cafe = "café"
print(cafe.count) // 4String.uppercased() -> StringReturns a new string made by replacing lowercase characters with uppercase ones.
Returns
String
Example
let s = "Hello World"
print(s.uppercased()) // "HELLO WORLD"String.lowercased() -> StringReturns a new string made by replacing uppercase characters with lowercase ones.
Returns
String
Example
let s = "Hello World"
print(s.lowercased()) // "hello world"String.hasPrefix(_ prefix: String) -> BoolReturns a Boolean indicating whether the string begins with the specified prefix.
Parameters
| Name | Type | Description |
|---|---|---|
| prefix | String | Prefix to test for. |
Returns
Bool
Example
let s = "Hello, World"
print(s.hasPrefix("Hello")) // true
print(s.hasPrefix("World")) // falseString.hasSuffix(_ suffix: String) -> BoolReturns a Boolean indicating whether the string ends with the specified suffix.
Parameters
| Name | Type | Description |
|---|---|---|
| suffix | String | Suffix to test for. |
Returns
Bool
Example
let s = "Hello, World"
print(s.hasSuffix("World")) // true
print(s.hasSuffix("Hello")) // falseString.contains(_ other: String) -> BoolReturns true if the string contains the given string or character.
Parameters
| Name | Type | Description |
|---|---|---|
| other | String | Substring to search for. |
Returns
Bool
Example
let s = "Hello, World"
print(s.contains("World")) // true
print(s.contains("xyz")) // falseString.split(separator: Character) -> [Substring]Returns the longest possible subsequences of the string, in order, around the separator.
Parameters
| Name | Type | Description |
|---|---|---|
| separator | Character | Character to split on. |
Returns
[Substring]
Example
let s = "a,b,c"
let parts = s.split(separator: ",")
// parts == ["a", "b", "c"]String.replacingOccurrences(of: String, with: String) -> StringReturns a new string in which all occurrences of a target string are replaced by another.
Parameters
| Name | Type | Description |
|---|---|---|
| of | String | String to replace. |
| with | String | Replacement string. |
Returns
String
Example
let s = "Hello, World"
let r = s.replacingOccurrences(of: "World", with: "Swift")
// r == "Hello, Swift"