Sometimes it is necessary to have a function that gets only the first several words in a string
. This can be helpful for user interfaces.
With Swift, we can count the first words, and return a new string
containing just those words. We must take a substring for this function.
To begin, we introduce the firstWords
function. This receives a String
containing the original text, and an integer that indicates the desired number of words.
string
with the enumerated()
function, which returns indexes and characters.string
range by using startIndex
and the index()
function. We return a String
based on that substring.func firstWords(source: String, count: Int) -> String { var words = count // Step 1: use enumerated over string. for (i, c) in source.enumerated() { // Step 2: check for space, and decrement words count. if c == " " { words -= 1 if words == 0 { // Step 3: get range for substring and return it. let r = source.startIndex..<source.index(source.startIndex, offsetBy: i) return String(source[r]) } } } // Step 4: return original string. return source } let value = "there are many reasons" // Test the first words method. let result1 = firstWords(source: value, count: 2) print(result1) let result2 = firstWords(source: value, count: 3) print(result2) let result3 = firstWords(source: value, count: 100) print(result3)there are there are many there are many reasons
With Swift it is possible to develop simple char
-counting methods that return substrings. The code is clear and reliable, and can be extended for more complex purposes.