The components(separatedBy:)
method is used to divide a string into substrings using the specified string separator.
string.components(separated: separator)
separator
: The separator that will be used to separate the substrings of the string string
. It can be a character or a string.
The value returned is an array of substrings of string
separated by the specified separator
.
Let’s look at the code below:
// import foundationimport Foundation// create some stringslet str1 = "welcome to Edpresso"let str2 = "A-Good-Day"// print substrings separated by a separatorprint(str1.components(separatedBy: " "))print(str2.components(separatedBy: "-"))
Foundation
framework. It is a framework containing several APIs like String
, Date
, and so on. It is useful when we want to use some of its functionalities. In this case, we want to use the functionality of the String
.components(separatedBy:)
is used to convert the strings to an array of substrings separated by the given separators. The results are printed using the print()
function to the console.