Consider the following extension:
extension Array where Element == String {
func foo(){
}
}
And consider the following string that I want to split so I can use the extension...
let string = "This|is|a|test"
let words = string.split(separator: "|")
The problem is words
is a [Substring]
and not [String]
so I can't call foo()
on it.
So in Swift 4, how do I split a string to return a [String]
and not a [Substring]
?
Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.
Use the string split in Java method against the string that needs to be divided and provide the separator as an argument. In this Java split string by delimiter case, the separator is a comma (,) and the result of the Java split string by comma operation will give you an array split.
Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
As Leo said above, you can use components(separatedBy:)
let string = "This|is|a|test"
let words = string.components(separatedBy: "|")
words.foo()
instead, that returns a [String]
.
If you want to stick with
split()
(e.g. because it has more options, such as to omit
empty subsequences), then you'll have to create a new array by converting each Substring
to a String
:
let string = "This|is|a|test"
let words = string.split(separator: "|").map(String.init)
words.foo()
Alternatively – if possible – make the array extension method more
general to take arguments conforming to the StringProtocol
protocol,
that covers both String
and Substring
:
extension Array where Element: StringProtocol {
func foo(){
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With