String
struct String
-
Returns a new String with the \n, \r, \v, “ ” and \r\n removed from the end of str,
"1Hello\r1\n".chomp #=> "1Hello\r1" "Hello\r\n\r\n".chomp #=> "Hello" "Hello\n".chomp #=> "Hello" "Hello ".chomp #=> "Hello" "Hello \r".chomp #=> "Hello" " Hello \r".chomp #=> " Hello" "".chomp #=> ""Declaration
Swift
var chomp: String -
Returns a new String with the seaprator removed from the end of str (if present).
"Hello\r\n".chomp("o\r\n") #=> "Hell" "Hello".chomp("o\r\n") #=> "Hello"If separator is an empty string, it will remove all trailing newlines from the string.
"Hello\r\n\r\n".chomp("") #=> "Hello" "Hello\r\n\r\r\n".chomp("") #=> "Hello\r\n\r"Declaration
Swift
func chomp(_ separator: String = "") -> StringParameters
separatorA string used to chomp from the end of the string
Return Value
A new string with the end of str being chomped from the receiver
-
Modifies str in place as described for .chomp(separator:), returning str.
Declaration
Swift
mutating func chomped(_ separator: String = "") -> StringParameters
separatorA string used to chomp from the end of the string
Return Value
Self
-
Return a new string with the last char removed from the receiver
"Hello\r\n\r\n".chop #=> "Hello\r\n" "Hello\r\n".chop #=> "Hello" "Hello\n\r".chop #=> "Hello\n" "Hello\n".chop #=> "Hello" "x".chop #=> ""This methods will return a empty string if the receiver length is less than or equal to 0.
"".chop.chop #=> ""Declaration
Swift
var chop: String -
Modifies str in place as described for .chop, returning str.
Declaration
Swift
mutating func choped() -> StringReturn Value
Self
-
Makes string empty.
var s = "xyz" s.cleared() #=> "" s #=> ""Declaration
Swift
mutating func cleared() -> StringReturn Value
A empty string
-
Each
strsparameter defines a set of characters to count. The intersection of these sets defines the characters to count in str.let a = "hello world" a.count("lo") #=> 5 a.count("lo", "o") #=> 2Any
strsthat starts with a caret ^ is negated.a.count("hello", "^l") #=> 4The sequence c1-c2 means all characters between c1 and c2.
a.count("ej-m") #=> 4The backslash character \ can be used to escape ^ or - and is otherwise ignored unless it appears at the end of a sequence or the end of a
strs."hello^world".count("\\^aeiou") #=> 4 "hello-world".count("a-eo") #=> 4 let c = "hello world\\r\\n" c.count("\\A") #=> 0 c.count("X\\-\\\\w") #=> 3Declaration
Swift
func count(_ strs: String...) -> IntParameters
strsAn array of string used to match the receiver string
Return Value
The count of all the matched characters
-
Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as
String#count(strs:).let a = "hello world" a.delete("lo") #=> "he wrd" a.delete("lo", "o") #=> "hell wrld" a.delete("hello", "^l") #=> "ll wrld" a.delete("ej-m") #=> "ho word" "hello^world".delete("\\^aeiou") #=> "hllwrld" "hello-world".delete("a-eo") #=> "hll-wrl" "hello-world".delete("a\\-eo") #=> "hllwrld" let c = "hello world\\r\\n" c.delete("\\A") #=> "hello world\\r\\n" c.delete("X\\-\\\\w") #=> "hello orldrn"See
See Also:String#count(strs:)Declaration
Swift
func delete(_ strs: String...) -> StringParameters
strsAn array of string used to match the receiver string
Return Value
A string with all chars in strs deleted
-
Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as
String#count(strs:).let a = "hello world" a.delete("lo") #=> "he wrd" a.delete("lo", "o") #=> "hell wrld" a.delete("hello", "^l") #=> "ll wrld" a.delete("ej-m") #=> "ho word" "hello^world".delete("\\^aeiou") #=> "hllwrld" "hello-world".delete("a-eo") #=> "hll-wrl" "hello-world".delete("a\\-eo") #=> "hllwrld" let c = "hello world\\r\\n" c.delete("\\A") #=> "hello world\\r\\n" c.delete("X\\-\\\\w") #=> "hello orldrn"See
See Also:String#count(strs:)Declaration
Swift
func delete(_ strs: [String]) -> StringParameters
strsAn array of string used to match the receiver string
Return Value
A string with all chars in strs deleted
-
Use
delete(strs:)to mutateselfin place, see alsodelete(strs:)Declaration
Swift
mutating func deleted(_ strs: String...) -> StringParameters
strsAn array of string used to match the receiver string
Return Value
Self
-
Reverses all characters in the string.
"Hello".reverse #=> "olleH"Declaration
Swift
var reverse: String -
Modifies str in place as described for .reverse, returning str.
Declaration
Swift
mutating func reversed() -> StringReturn Value
Self
-
Divides str into substrings based on a delimiter, returning an array of these substrings.
" now's the time".split #=> ["now's", "the", "time"] " now's\nthe time\n\t".split #=> ["now's", "the", "time"]Declaration
Swift
var split: [String] -
Divides str into substrings based on a delimiter, returning an array of these substrings. (default is “ ”) If pattern is a
String, then its contents are used as the delimiter when splitting str."mellow yellow".split("ello") #=> ["m", "w y", "w"] "1,2,,3,4,,".split(",") #=> ["1", "2", "", "3", "4"]If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
" now's the time".split(" ") #=> ["now's", "the", "time"]If pattern is an empty string, str is split into chars.
"hello".split("") #=> ["h", "e", "l", "l", "o"]If pattern is a
Regex, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters."hello".split("l+") #=> ["he", "o"]If pattern contains groups, the respective matches will be returned in the array as well.
"red yellow and blue".split("[ae ]") #=> ["r", "d", "y", "llow", "", "nd", "blu"]Declaration
Swift
func split(_ separator: RegexConvertible = " ", limit: Int = 0) -> [String]Parameters
separatorA string to seperate the receiver
Return Value
An array of string which separated by separator
-
If integer is greater than the length of str, returns a new String of length integer with str left justified and padded with padstr; otherwise, returns str.
"hello".ljust(20) #=> "hello " "hello".ljust(20, "1234") #=> "hello123412341234123" "hello".ljust(4) #=> "hello"Declaration
Swift
func ljust(_ length: Int, _ padding: String = " ") -> StringParameters
lengthA int to indicates the return length of the new string
paddingA string used to padding str
Return Value
A new string use padding string to ljust
-
If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str.
"hello".rjust(20) #=> " hello" "hello".rjust(20, "1234") #=> "123412341234123hello" "hello".rjust(4) #=> "hello"Declaration
Swift
func rjust(_ length: Int, _ padding: String = " ") -> StringParameters
lengthA int to indicates the return length of the new string
paddingA string used to padding str
Return Value
A new string use padding string to rjsut
-
Centers str in width. If width is greater than the length of str, returns a new String of length width with str centered and padded with padstr; otherwise, returns str.
"hello".center(20) #=> " hello " "hello".center(20, "123") #=> "1231231hello12312312" "hello".center(4) #=> "hello"Declaration
Swift
func center(_ width: Int, _ padding: String = " ") -> StringParameters
lengthA int to indicates the return length of the new string
paddingA string used to padding str
Return Value
A new string use padding string to center
-
Returns a copy of str with leading and trailing whitespace removed.
"\t \nhello ".strip #=> "hello" "\t hello ".strip #=> "hello" "hello ".strip #=> "hello"Declaration
Swift
var strip: String -
Removes leading and trailing whitespace from str.
See
See Also:String#stripDeclaration
Swift
mutating func stripped() -> StringReturn Value
Self
-
Returns a copy of str with leading whitespace removed.
"\t \nhello".lstrip #=> "hello" "\t hello ".lstrip #=> "hello "See
See Also:String#rstripandString#stripDeclaration
Swift
var lstrip: String -
Removes leading whitespace from str.
See
See Also:String#rstripandString#stripDeclaration
Swift
mutating func lstripped() -> StringReturn Value
Self
-
Removes trailing whitespace from str.
See
See Also:String#rstripandString#stripDeclaration
Swift
mutating func rstripped() -> StringReturn Value
Self
-
Concatenates the given str to the receiver
"Hello".concat(" World") #=> "Hello World"Declaration
Swift
func concat(_ other: String) -> StringParameters
otherA string use to concat to the receiver
Return Value
A new string with self + other
-
Similar to
appendmethod, prepend another string to the receiver.var str = "yz" str.prepend("x") #=> "xyz" str #=> "xyz"Declaration
Swift
mutating func prepend(_ other: String) -> StringParameters
otherAnothing string
Return Value
Self
-
Replace the receiver string by the passing parameter
var str = "yz" str.replace("x") #=> "x" str #=> "x"Declaration
Swift
mutating func replace(_ other: String) -> StringParameters
otherA new string used to replace self
Return Value
Self
-
Searches sep or pattern (Regex) in the string and returns the part before it, the match, and the part after it.
"hello".partition("l") #=> ["he", "l", "lo"]If it is not found, returns two empty strings and str.
"hello".partition("le") #=> ["hello", "", ""]Declaration
Swift
func partition(_ pattern: RegexConvertible) -> [String]Parameters
patternA string used to separate the receiver
Return Value
An array of string which separated by seperator
-
Searches sep or pattern (regexp) in the string from the end of the string, and returns the part before it, the match, and the part after it.
"hello".rpartition("l") #=> ["hel", "l", "o"]If it is not found, returns two empty strings and str.
"hello".rpartition("le") #=> ["", "", "hello"]Declaration
Swift
func rpartition(_ pattern: RegexConvertible) -> [String]Parameters
patternA string used to separate the receiver
Return Value
An array of string which separated by seperator
-
Returns a new string with all occurrences of the patterns removed.
let str = "foo bar test" str.remove(" test") #=> "foo bar" str.remove(" test", "bar") #=> "foo " str.remove(".") #=> "" str #=> "foo bar test" "returns a new string with all occurrences of the strs removed".remove("s") #=> "return a new tring with all occurrence of the tr removed"Declaration
Swift
func remove(_ patterns: RegexConvertible...) -> StringParameters
patternsAn array of string which will be converted to
RegexpReturn Value
A new string with all occurrences of the patterns removed
-
Returns a new string with all occurrences of the patterns removed.
let str = "foo bar test" str.remove(" test") #=> "foo bar" str.remove(" test", "bar") #=> "foo " str.remove(".") #=> "" str #=> "foo bar test" "returns a new string with all occurrences of the strs removed".remove("s") #=> "return a new tring with all occurrence of the tr removed"Declaration
Swift
func remove(_ patterns: [RegexConvertible]) -> StringParameters
patternsAn array of string which will be converted to
RegexpReturn Value
A new string with all occurrences of the patterns removed
-
Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.
" Multi-line\n string ".squish #=> "Multi-line string" " foo bar \n \t boo ".squish #=> "foo bar boo"Declaration
Swift
var squish: String -
Performs a destructive squish in place. See
squish.var lines = " Multi-line\n string " lines.squished() #=> "Multi-line string" lines #=> "Multi-line string"Declaration
Swift
mutating func squished() -> StringReturn Value
Self
-
Returns a new string where runs of the same character that occur in this str are replaced by a single character. All runs of identical characters are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon" " now is the".squeeze(" ") #=> " now is the" "putters shoot balls".squeeze("to") #=> "puters shot balls"Declaration
Swift
var squeeze: String -
Returns a new string where runs of the same character that occur in this str are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon" " now is the".squeeze(" ") #=> " now is the" "putters shoot balls".squeeze("to") #=> "puters shot balls"Declaration
Swift
func squeeze(_ str: String) -> StringParameters
strA str contains all characters need to squeeze
Return Value
A new string with the same character squeezed
-
Squeezes str in place with returning nothing.
var words = "yellow moon" words.squeeze() #=> "yelow mon" words #=> "yelow mon"Declaration
Swift
mutating func squeezed(_ str: String) -> StringParameters
strA str contains all characters need to squeeze
Return Value
Self
-
Truncates the receiver string after a given length if string is longer than length. The last characters will be replaced with the omission string (defaults to
…
) for a total length not exceeding lengthlet str = "Once upon a time in a world far far away" str.truncate(27) #=> "Once upon a time in a wo..." let anotherStr = "And they found that many people were sleeping better." anotherStr.truncate(25, omission: "... (continued)") #=> "And they f... (continued)" let shortStr = "test" shortStr.truncate(3, omission: "... (continued)") #=> "test"Declaration
Swift
func truncate(_ at: Int, omission: String = "...") -> StringParameters
atA interger indicates the length of truncated string must be less than
omissionA string used to replace the last characters (defaults to
…
)Return Value
A new string with length exceeding
atcharacters removed
-
Indents the lines in the receiver
" foo".indent(2) #=> "\t\tfoo" " foo".indent(2, " ") #=> " foo" " foo\n\tbar".indent(2, " ") #=> " foo\n bar"Declaration
Swift
func indent(_ amount: Int, _ indentString: String = "\t") -> StringParameters
amountA int specifies the amount of indentString for one level idnentation
indentStringA string specifies which indent string to use. The default is \t.
Return Value
A string indented with current methods
-
Indents the lines in the receiver and changes self
var str = " foo\n\tbar" str.indented(2, " ") str #=> " foo\n bar"Declaration
Swift
mutating func indented(_ amount: Int, _ indentString: String = "\t")Parameters
amountA int specifies the amount of indentString for one level idnentation
indentStringA string specifies which indent string to use. The default is \t.
-
Returns
trueif receiver contains the given strings or characters array." ".isInclude("he") #=> false "he".isInclude("he") #=> true "ohe".isInclude("he") #=> true "ohe".isInclude("he", "oooo") #=> true "oe".isInclude("he", "dajkldjda") #=> falseDeclaration
Swift
func isInclude(_ substrings: String...) -> BoolParameters
substringsAn array of strings or characters
Return Value
A bool value indicates whether the string includes the other string
-
Returns
trueif receiver contains the given strings or characters array." ".isInclude("he") #=> false "he".isInclude("he") #=> true "ohe".isInclude("he") #=> true "ohe".isInclude("he", "oooo") #=> true "oe".isInclude("he", "dajkldjda") #=> falseDeclaration
Swift
func isInclude(_ substrings: [String]) -> BoolParameters
substringsAn array of strings or characters
Return Value
A bool value indicates whether the string includes the other string
-
Returns
trueif receiver does not contains the given strings or characters array." ".isExlude("he") #=> true "he".isExlude("he") #=> false "ohe".isExlude("he") #=> false "ohe".isExlude("he", "oooo") #=> false "oe".isExlude("he", "dajkldjda") #=> trueDeclaration
Swift
func isExlude(_ substrings: String...) -> BoolParameters
substringsAn array of strings or characters
Return Value
A bool value indicates whether the string excludes the other string
-
Returns
trueif receiver does not contains the given strings or characters array." ".isExlude("he") #=> true "he".isExlude("he") #=> false "ohe".isExlude("he") #=> false "ohe".isExlude("he", "oooo") #=> false "oe".isExlude("he", "dajkldjda") #=> trueDeclaration
Swift
func isExlude(_ substrings: [String]) -> BoolParameters
substringsAn array of strings or characters
Return Value
A bool value indicates whether the string excludes the other string
-
Returns true if str starts with one of the prefixes given.
"he".isStartWith("he") #=> true "ohe".isStartWith("he", "oooo") #=> false "oe".isStartWith("o", "dajkldjda") #=> trueDeclaration
Swift
func isStartWith(_ substrings: String...) -> BoolParameters
substringsAn array of prefixes
Return Value
A bool value indicates whether the string starts with another string in array
-
Returns true if str starts with one of the prefixes given.
"he".isStartWith("he") #=> true "ohe".isStartWith("he", "oooo") #=> false "oe".isStartWith("o", "dajkldjda") #=> trueDeclaration
Swift
func isStartWith(_ substrings: [String]) -> BoolParameters
substringsAn array of prefixes
Return Value
A bool value indicates whether the string starts with another string in array
-
Returns true if str ends with one of the suffixes given.
" ".isEndWith("he") #=> false "he".isEndWith("he") #=> true "ohe".isEndWith("he") #=> true "ohe".isEndWith("he", "oooo") #=> true "oe".isEndWith("he", "dajkldjda") #=> falseDeclaration
Swift
func isEndWith(_ substrings: String...) -> BoolParameters
substringsAn array of suffixes
Return Value
A bool value indicates whether the string ends with another string in array
-
Returns true if str ends with one of the suffixes given.
" ".isEndWith("he") #=> false "he".isEndWith("he") #=> true "ohe".isEndWith("he") #=> true "ohe".isEndWith("he", "oooo") #=> true "oe".isEndWith("he", "dajkldjda") #=> falseDeclaration
Swift
func isEndWith(_ substrings: [String]) -> BoolParameters
substringsAn array of suffixes
Return Value
A bool value indicates whether the string ends with another string in array
-
Converts pattern to a
NSReguarExpression, then returns a bool value indicates whether theNSReguarExpressionis matched receiver or not." ".isMatch("he") #=> false "he".isMatch("he") #=> true "oe".isMatch("he") #=> false "oe".isMatch(".e") #=> true "abcdefghijklmnopqrstuvwxyz".isMatch(".*") #=> trueIf the second parameter is present, it specifies the position in the string to begin the search.
"ohe".isMatch("he", 2) #=> falseDeclaration
Swift
func isMatch(_ pattern: String, _ start: Int = 0) -> BoolParameters
patternA string pattern
startA int specifies the position in the string to begin the search
Return Value
a true or false indicates whether the
NSReguarExpressionis matched receiver or not -
Returns true is the recevier string’s characters are all whitespaces, like
\r,\n,\tand." ".isBlank #=> true "\t\n\r\n".isBlank #=> true "\t\nblah".isBlank #=> falseDeclaration
Swift
var isBlank: Bool -
Returns true is the recevier string’s characters are all downcase.
"HELLO".isDowncase #=> false "HELLOo".isDowncase #=> false "hello".isDowncase #=> trueDeclaration
Swift
var isDowncase: Bool -
Returns true is the recevier string’s characters are all upcase.
"HELLO".isUpcase #=> true "HELLOo".isUpcase #=> falseDeclaration
Swift
var isUpcase: Bool
-
Splits str using the supplied parameter as the record separator
\n, passing each substring with separator in turn to the supplied closure.var results: [String] = [] "Hello\nWorld".eachLine { results.append($0) } results #=> ["Hello\n", "World"]If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.
var results: [String] = [] "Hello\nWorld".eachLine("l") { results.append($0) } results #=> ["Hel", "l", "o\nWorl", "d"]Declaration
Swift
func eachLine(_ separator: String = "\n", closure: (String) -> Void)Parameters
separatorA string used to separate the receiver string
closureA closure reveives String as parameter which is separated by the separator
-
Passes each character as string in the receiver to the given closure.
var results: [String] = [] "Hello\n".eachChar { results.append($0) } results #=> ["H", "e", "l", "l", "o", "\n"]Declaration
Swift
func eachChar(closure: (String) -> Void)Parameters
closureA closure receives all characters as String
-
Undocumented
Declaration
Swift
struct String
-
Returns the length of string.
Declaration
Swift
var length: Int -
Returns the length of string.
Declaration
Swift
var size: Int -
Returns the length of string.
Declaration
Swift
var count: Int
-
Returns the result of interpreting leading characters in str as an integer base (between 2 and 36), default is 10, extraneous characters past the end of a valid number are ignored.
"0a".to_i(16) #=> 10 "0xa".to_i(16) #=> 0 "12".to_i #=> 12 "-1100101".to_i(2) #=> -101 "1100101".to_i(2) #=> 101 "1100101".to_i(8) #=> 294977 "1100101".to_i(10) #=> 1100101 "1100101".to_i(16) #=> 17826049This method returns 0 when base is invalid.
"0a".to_i(1) #=> 0 "0a".to_i(37) #=> 0If there is not a valid number at the start of str, 0 is returned.
"-".to_i #=> 0 "d-1".to_i #=> 0 "0a".to_i #=> 0 "hello".to_i #=> 0 "".to_i #=> 0 " ".to_i #=> 0Declaration
Swift
var to_i: Int -
Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error.
"-".to_hex #=> 0 "0xa".to_hex #=> 10 "-0xa".to_hex #=> -10 "a".to_hex #=> 10Declaration
Swift
var to_hex: Int -
An alias to
String#to_hexmethod."-".hex #=> 0 "0xa".hex #=> 10 "-0xa".hex #=> -10 "a".hex #=> 10Declaration
Swift
var hex: Int -
Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number.
"123".oct #=> 83 "-377".oct #=> -255 "377bad".oct #=> 255Returns 0 if the conversion fails.
"bad".oct #=> 0Declaration
Swift
var oct: Int -
Return the Integer ordinal of a one-character string.
"a".ord #=> 97 "ab".ord #=> 97 "b".ord #=> 98Return 0 if the receiver is an empty string.
"".ord #=> 0Declaration
Swift
var ord: UInt32 -
Returns the result of interpreting leading characters in str as an integer base (between 2 and 36), default is 10, extraneous characters past the end of a valid number are ignored.
"0a".to_i(16) #=> 10 "0xa".to_i(16) #=> 0 "12".to_i #=> 12 "-1100101".to_i(2) #=> -101 "1100101".to_i(2) #=> 101 "1100101".to_i(8) #=> 294977 "1100101".to_i(10) #=> 1100101 "1100101".to_i(16) #=> 17826049This method returns 0 when base is invalid.
"0a".to_i(1) #=> 0 "0a".to_i(37) #=> 0If there is not a valid number at the start of str, 0 is returned.
"-".to_i #=> 0 "d-1".to_i #=> 0 "0a".to_i #=> 0 "hello".to_i #=> 0 "".to_i #=> 0 " ".to_i #=> 0Declaration
Swift
func to_i(_ base: Int = 10) -> IntParameters
baseA int indicates the integer base
Return Value
A integer based on the integer base
-
An alias to
to_doublebut returnsFloatinstead.Declaration
Swift
var to_f: Float -
Returns the result of interpreting leading characters in str as a double Extraneous characters past the end of a valid number are ignored.
"0a".to_double #=> 0 "1100101.11".to_double #=> 1100101.11 "123.456".to_double #=> 123.456 "123.456ddddd".to_double #=> 123.456 ".456ddddd".to_double #=> 0.456If there is not a valid number at the start of str, 0.0 is returned.
"-".to_double #=> 0 "d-1".to_double #=> 0 "0a".to_double #=> 0 "..12".to_double #=> 0 "hello".to_double #=> 0Declaration
Swift
var to_double: Double -
Returns the result of interpreting the receiver in different standard. This methods returns
nil, if the receiver is not in Custom, ISO8601, RFC2822 or CTime form."Sun Mar 19 01:04:21 2017".to_datetime! #=> 2017-03-19 01:04:21 +0000 "2017-03-19 00:35:36 +0800".to_datetime! #=> 2017-03-19 00:35:36 +0800See
See Also: DateFormatDeclaration
Swift
var to_datetime: Date?
-
Try to convert
selfto aRegexwhich used to match string or pass as parameter into some methods.Declaration
Swift
public func to_regex(_ literal: Bool = false) -> RegexParameters
literalA bool indicate whether match the receiver literally
Return Value
A
Regexstruct contains the receiver as a pattern
-
If you pass a single
Int, returns a substring of one character at that position. The first character of the string is at position 0, the next at position 1, and so on."Hello".at(1) #=> "e" "Hello".at(2) #=> "l" "Hello".at(4) #=> "o" "Hello".at(5) #=> nil "Hello".at(10) #=> nilIf a
Rangeis supplied, a substring containing characters at offsets given by the range is returned."Hello".at(1...2) #=> "el" "Hello".at(1...4) #=> "ello" "Hello".at(1...5) #=> "ello" "Hello".at(4...9) #=> "o" "Hello".at(1..<2) #=> "e" "Hello".at(1..<4) #=> "ell" "Hello".at(1..<5) #=> "ello" "Hello".at(1..<6) #=> "ello"Returns an empty string if the beginning of the range is greater than the end of the string.
"Hello".at(5...9) #=> "" "Hello".at(5..<9) #=> ""Returns
nilif the initial offset falls outside the string."Hello".at(6...9) #=> nil "Hello".at(6..<9) #=> nilDeclaration
Swift
func at(_ pos: Int) -> String?Parameters
posA specific position in the receiver string
Return Value
A substring of one character at that position or nil
-
If you pass a single
Int, returns a substring of one character at that position. The first character of the string is at position 0, the next at position 1, and so on."Hello".at(1) #=> "e" "Hello".at(2) #=> "l" "Hello".at(4) #=> "o" "Hello".at(5) #=> nil "Hello".at(10) #=> nilIf a
Rangeis supplied, a substring containing characters at offsets given by the range is returned."Hello".at(1...2) #=> "el" "Hello".at(1...4) #=> "ello" "Hello".at(1...5) #=> "ello" "Hello".at(4...9) #=> "o" "Hello".at(1..<2) #=> "e" "Hello".at(1..<4) #=> "ell" "Hello".at(1..<5) #=> "ello" "Hello".at(1..<6) #=> "ello"Returns an empty string if the beginning of the range is greater than the end of the string.
"Hello".at(5...9) #=> "" "Hello".at(5..<9) #=> ""Returns
nilif the initial offset falls outside the string."Hello".at(6...9) #=> nil "Hello".at(6..<9) #=> nilDeclaration
Swift
func at(_ range: CountableClosedRange<Int>) -> String?Parameters
rangeA range used to substring the receiver
Return Value
A substring containing characters at offsets given by the range is returned
-
If you pass a single
Int, returns a substring of one character at that position. The first character of the string is at position 0, the next at position 1, and so on."Hello".at(1) #=> "e" "Hello".at(2) #=> "l" "Hello".at(4) #=> "o" "Hello".at(5) #=> nil "Hello".at(10) #=> nilIf a
Rangeis supplied, a substring containing characters at offsets given by the range is returned."Hello".at(1...2) #=> "el" "Hello".at(1...4) #=> "ello" "Hello".at(1...5) #=> "ello" "Hello".at(4...9) #=> "o" "Hello".at(1..<2) #=> "e" "Hello".at(1..<4) #=> "ell" "Hello".at(1..<5) #=> "ello" "Hello".at(1..<6) #=> "ello"Returns an empty string if the beginning of the range is greater than the end of the string.
"Hello".at(5...9) #=> "" "Hello".at(5..<9) #=> ""Returns
nilif the initial offset falls outside the string."Hello".at(6...9) #=> nil "Hello".at(6..<9) #=> nilDeclaration
Swift
func at(_ range: CountableRange<Int>) -> String?Parameters
rangeA range used to substring the receiver
Return Value
A substring containing characters at offsets given by the range is returned
-
Returns the first character as
String."hello".first #=> "h" "".first #=> ""Declaration
Swift
var first: String -
Returns the first character as
String. An alias method forString#first."hello".chr #=> "h" "".chr #=> ""Declaration
Swift
var chr: String -
Returns the first character as
String.let str = "people" str.first #=> "p" str.first() #=> "p"If a limit is supplied, returns a substring from the beginning of the string until it reaches the limit value.
str.first(1) #=> "p" str.first(2) #=> "pe" str.first(4) #=> "peop"If the given limit is greater than or equal to the string length, returns a copy of self.
str.first(50) #=> "people"If the given limit is less than the string length, returns a empty string.
str.first(0) #=> "" str.first(-2) #=> ""Declaration
Swift
func first(_ limit: Int = 1) -> StringParameters
limitA integer indicates how many characters would extract from the receiver
Return Value
A substring containing characters from the beginning to given
num -
Returns the last character of the reveiver of
String."hello".last #=> "o" "".last #=> ""Declaration
Swift
var last: String -
Returns the last character of the reveiver of
String.let str = "people" str.last #=> "e" str.last() #=> "e"If a limit is supplied, returns a substring from the end of the string until it reaches the limit value (counting backwards).
str.last(1) #=> "e" str.last(2) #=> "le" str.last(4) #=> "ople"If the given limit is greater than or equal to the string length, returns a copy of self.
str.last(50) #=> "people"If the given limit is less than the string length, returns a empty string.
str.last(0) #=> "" str.last(-2) #=> ""Declaration
Swift
func last(_ limit: Int = 1) -> StringParameters
limitA integer indicates how many characters would extract from the receiver
Return Value
A substring containing characters from the end of the string until it reaches the limit value (counting backwards)
-
Returns a substring from the given position to the end of the string.
let str = "hello" str.from(0) #=> "hello" str.from(3) #=> "lo" str.from(5) #=> ""If the position is negative, it is counted from the end of the string.
str.from(-5) #=> "" str.from(-6) #=> "" str.from(-2) #=> "lo" str.from(-1) #=> "o" str.from(-2) #=> "lo"Declaration
Swift
func from(_ num: Int) -> String?Parameters
numA position indicates the start position of substring
Return Value
A substring from the given position to the end of the string
-
Returns a substring from the beginning of the string to the given position(included).
let str = "hello" str.to(0) #=> "h" str.to(3) #=> "hell" str.to(4) #=> "hello" str.to(5) #=> "hello"If the position is negative, it is counted from the end of the string.
str.to(-2) #=> "hell" str.to(-6) #=> "" str.to(-7) #=> ""Declaration
Swift
func to(_ num: Int) -> String?Parameters
numA position indicates the end position of substring
Return Value
A substring from the beginning of the string to the given position
-
Returns a substring in the range with from…to, both sides included.
let str = "hello" str.range(0, 0) #=> "h" str.range(0, 1) #=> "he" str.range(0, 10) #=> "hello" str.range(3, 10) #=> "lo"Declaration
Swift
func range(_ from: Int, _ to: Int) -> String?Parameters
fromA position indicates the start position of substring
toA position indicates the end position of substring
Return Value
A substring within the range of the string to the given position
-
Returns a substring from the given position to the end of the string. Uses
NSStringmethod substring(from:) to get a substring from the receiver.let str = "hello" "Hello".substring(from: 1) #=> "ello" "H\n11".substring(from: 2) #=> "11"Declaration
Swift
func substring(from: Int) -> StringParameters
fromA position indicates the start position of substring
Return Value
A substring from the given position to the end of the string
-
Returns a substring from the beginning of the string to the given position(excluded). Uses
NSStringmethod substring(to:) to get a substring from the receiver.let str = "hello" "Hello".substring(to: 1) #=> "H" "H\n11".substring(to: 2) #=> "H\n"Declaration
Swift
func substring(to: Int) -> StringParameters
toA position indicates the end position of substring
Return Value
A substring from the beginning of the string to the given position
-
Returns the index of the first occurrence of the given substring in str. Returns
nilif not found."hello".index("e") #=> 1 "hello".index("l") #=> 2 "hello".index("a") #=> nilDeclaration
Swift
func index(_ str: String) -> Int?Parameters
strA substring used to find index in the receiver
Return Value
The index of the first occurrence of the given substring in str or
nil -
Returns the index of the last occurrence of the given substring in str. Returns
nilif not found."hello".rindex("e") #=> 1 "hello".rindex("l") #=> 3 "hello".rindex("x") #=> nilDeclaration
Swift
func rindex(_ str: String) -> Int?Parameters
strA substring used to find rindex in the receiver
Return Value
The index of the last occurrence of the given substring in str or
nil
-
Returns all characters in string form intead of characters form
"abcde".chars #=> ["a", "b", "c", "d", "e"]Declaration
Swift
var chars: [String] -
Returns all lines in string form separated by newline
\n."a\nb\nc\nd\ne".lines #=> ["a", "b", "c", "d", "e"]Declaration
Swift
var lines: [String] -
Returns all lines in string form separated by separator.
"abcde".chars #=> ["a", "b", "c", "d", "e"] "a\tb\tc\td\te".lines("\t") #=> ["a", "b", "c", "d", "e"]Declaration
Swift
func lines(_ separator: String = "\n") -> [String]Parameters
separatorA separator used to separate the receiver string
Return Value
An array of strings separated by separator
-
Converts pattern to a
Regex, then invokes itsRegex#match(str:)method. If the second parameter is present, it specifies the position in the string to begin the search.let matchData = "hello".match("(.)ll(o)")! #=> <MatchData> matchData.match #=> "ello" matchData.captures[0] #=> "e" matchData.captures[1] #=> "o" let matchData = "hello".match("aha") #=> nilDeclaration
Swift
func match(_ pattern: RegexConvertible, _ pos: Int = 0) -> MatchData?Parameters
patternA pattern conforms to
RegexConvertibleposA int specifies the position in the string to begin the search
Return Value
A
MatchDatainstance contains all match results in it -
Converts pattern to a
Regex, then invokes itsRegex#scans(str:)method which returns an sequence ofMatchData.let str = "abcxxabcxxsbc" let scanResults = str.scan("(.)bc") scanResults[0].to_a #=> ["abc", "a"] scanResults[1].to_a #=> ["abc", "a"] scanResults[2].to_a #=> ["sbc", "s"]Declaration
Swift
func scan(_ pattern: RegexConvertible, closure: ((String) -> Void)? = nil) -> [MatchData]Parameters
patternA pattern conforms to
RegexConvertibleclosureA closure accepts the matching result as input and return output to change the origianl string
Return Value
An array of
MatchDatainstances contains all match results in it -
Converts pattern to a
Regex, then invokes its match(pattern:) method to get theMatchDataand replace the first matchig result with passing str."hello".sub("l", "abc") #=> "heabclo" "hello".sub("le", "lll") #=> "hello" "hello".sub(".", "a") #=> "aello"Declaration
Swift
func sub(_ pattern: RegexConvertible, _ str: String) -> StringParameters
patternA pattern conforms to
RegexConvertiblestrA string to replace the matching substring
Return Value
A new string with str replacing the matched result
-
Converts pattern to a
Regex, then invokes its match(pattern:) method to get theMatchDataand replace the first matchig result with passing str, and eventually mutating itself.var hello = "hello" hello.subed("l", "abc") #=> "heabclo" hello #=> "heabclo"Declaration
Swift
mutating func subed(_ pattern: RegexConvertible, _ str: String) -> StringParameters
patternA pattern conforms to
RegexConvertiblestrA string to replace the matching substring
Return Value
Self
-
Converts pattern to a
Regex, then invokes its matchAll(pattern:) method to get theMatchDataarray and replace the all matchig result with passing str."hello".gsub("l", "abc") #=> "heabcabco" "hello".gsub("le", "lll") #=> "hello" "hello".gsub(".".literal, "lll") #=> "hello" "hello".gsub(".", "lll") #=> "lll" * 5 "hello".gsub("^he", "lll") #=> "lllllo"Declaration
Swift
func gsub(_ pattern: RegexConvertible, _ str: String) -> StringParameters
patternA pattern conforms to
RegexConvertiblestrA string to replace the matching substring
Return Value
A new string with str replacing the matched result
-
Converts pattern to a
Regex, then invokes its matchAll(pattern:) method to get theMatchDataarray and replace the all matchig result with passing str, and eventually mutating itself.var hello = "hello" hello.gsubed("l", "abc") #=> "heabcabco" hello #=> "heabcabco"Declaration
Swift
mutating func gsubed(_ pattern: RegexConvertible, _ str: String) -> StringParameters
patternA pattern conforms to
RegexConvertiblestrA string to replace the matching substring
Return Value
Self
-
Converts pattern to a
Regex, then invokes its matchAll(pattern:) method to get theMatchDataarray and invoke the closure with all matchig result and replace current string with the invocation of the closure.let result = "my name is draven".gsub("\\b(?<!['’`])[a-z]") { _ in return "a" } result #=> "ay aame as araven"Declaration
Swift
func gsub(_ pattern: RegexConvertible, closure: (String) -> String) -> StringParameters
patternA pattern conforms to
RegexConvertibleclosureA closure accepts the matching result as input and return output to change the origianl string
Return Value
A new string with str replacing the matched result
-
Converts pattern to a
Regex, then invokes its matchAll(pattern:) method to get theMatchDataarray and invoke the closure with all matchig result and replace current string with the invokation of the closure , and eventually mutating itself.var intro = "my name is draven" intro.gsubed("\\b(?<!['’`])[a-z]") { _ in return "a" } #=> "ay aame as araven" intro #=> "ay aame as araven"Declaration
Swift
mutating func gsubed(_ pattern: RegexConvertible, closure: (String) -> String) -> StringParameters
patternA pattern conforms to
RegexConvertibleclosureA closure accepts the matching result as input and return output to change the origianl string
-
An enum used to control the output of camelize as parameter
- upper: Return the UppcaseCamelCase when specified
- lower: Return the lowerCamelCase when specified
Declaration
Swift
public enum LetterCase -
By default,
camelizeconverts strings to UpperCamelCase."os_version".camelize #=> "OsVersion" "os_version_ten".camelize #=> "OsVersionTen" "os_version_TEn".camelize #=> "OsVersionTen"If the argument to camelize is set to
.lowerthen camelize produces lowerCamelCase."os_version".camelize(.lower) #=> "osVersion"See also
LetterCaseDeclaration
Swift
func camelize(_ firstLetter: LetterCase = .upper) -> StringParameters
firstLetterA flag to control result between UpperCamelCase(.upper) and lowerCamelCase(.lower), See also LetterCase
Return Value
A string converts to camel case
-
Creates a foreign key name from a class name.
"people".foreignKey #=> "people_id" "people".foreignKey #=> "people_id" "MessageQueue".foreignKey #=> "message_queue_id"Separate flag sets whether the method should put ’_’ between the name and ‘id’.
"MessageQueue".foreignKey(false) #=> "message_queueid"Declaration
Swift
func foreignKey(_ separate: Bool = true) -> StringParameters
separateA bool value sets whether the method should put ’_’ between the name and ‘id’
Return Value
A foreign key name string
-
Converts strings to UpperCamelCase.
"os_version".camelize #=> "OsVersion" "os_version_ten".camelize #=> "OsVersionTen" "os_version_TEn".camelize #=> "OsVersionTen"See
See Also:String#camelize(firstLetter:)Declaration
Swift
var camelize: String -
Returns the plural form of the word in the string.
Declaration
Swift
var pluralize: String -
Returns the plural form of the word in the string.
"person".pluralize #=> "people" "monkey".pluralize #=> "monkeys" "user".pluralize #=> "users" "man".pluralize #=> "men"If the parameter count is specified, the singular form will be returned if count == 1.
"men".pluralize(1) #=> "man"For any other value of count the plural will be returned.
Declaration
Swift
func pluralize(_ count: Int = 2) -> StringParameters
countIf specified, the singular form will be returned if count == 1
Return Value
A string in plural form of the word
-
The reverse of
pluralize, returns the singular form of a word in a string."people".singularize #=> "person" "monkeys".singularize #=> "monkey" "users".singularize #=> "user" "men".singularize #=> "man"Declaration
Swift
var singularize: String -
The reverse of
camelize. Makes an underscored, lowercase form from the expression in the string."OsVersionTen".underscore #=> "os_version_ten" "osVersionTen".underscore #=> "os_version_ten" "osVerSionTen".underscore #=> "os_ver_sion_ten"Declaration
Swift
var underscore: String -
Creates the name of a table. This method uses the
String#pluralizemethod on the last word in the string."RawScaledScorer".tableize #=> "raw_scaled_scorers" "egg_and_ham".tableize #=> "egg_and_hams" "fancyCategory".tableize #=> "fancy_categories"Declaration
Swift
var tableize: String -
Creates a foreign key name from a class name.
"people".foreignKey #=> "people_id" "people".foreignKey #=> "people_id" "MessageQueue".foreignKey #=> "message_queue_id"Declaration
Swift
var foreignKey: String
-
Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.
"Hello".downcase #=> "hello" "HellHEo".downcase #=> "hellheo"Declaration
Swift
var downcase: String -
Downcases the contents of the receiver
var hello = "Hello" hello.downcased() #=> "hello" hello #=> "hello"Declaration
Swift
mutating func downcased() -> StringReturn Value
Self
-
Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.
"Hello".upcase #=> "HELLO" "HellHEo".upcase #=> "HELLHEO"Declaration
Swift
var upcase: String -
Upcases the contents of the receiver
var hello = "Hello" hello.upcased() #=> "HELLO" hello #=> "HELLO"Declaration
Swift
mutating func upcased() -> StringReturn Value
Self
-
Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
"HellHEo".swapcase #=> "hELLheO"Declaration
Swift
var swapcase: String -
Equivalent to
swapcase, but modifies the receiver in place.let hello = "HellHEo" hello.swapcased() #=> "hELLheO" hello #=> "hELLheO"Declaration
Swift
mutating func swapcased() -> StringReturn Value
Self
View on GitHub
String Extension Reference