Example. 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.
Step 1 We loop over the source string with the enumerated() function, which returns indexes and characters.
Step 2 We detect space characters. When a space is encountered, we reduce the remaining words count.
Step 3 Here compute the string range by using startIndex and the index() function. We return a String based on that substring.
Step 4 If the number of words specified was more than the number of spaces in the string, we just return the original.
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.