Swift String Exercises: Create a new string of length three from a given string of odd length from its middle
Swift String Programming: Exercise-15 with Solution
Write a Swift program to create a new string of length three from a given string of odd length from its middle. The string length must be three.
Pictorial Presentation:
Sample Solution:
Swift Code:
import Foundation
func middle_three_char(_ input: String) -> String {
let chars = input.characters
let middle_num = (chars.count - 1) / 2
let first_num = middle_num - 1
let third_num = middle_num + 1
let first_index = input.index(chars.startIndex, offsetBy: first_num)
let third_index = input.index(chars.startIndex, offsetBy: third_num + 1)
let middle_range = first_index ..< third_index
let result = input.substring(with: middle_range)
return result
}
print(middle_three_char("Swift"))
print(middle_three_char("abcde"))
Sample Output:
wif bcd
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to create a new string made of the first and last n chars from a given string. The string length will be at least n.
Next: Write a Swift program to concat two given strings and return the new string. If the new string creates a double character then omit one of the character. so "vwx" and "xyz" will return "vwxyz".
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/swift-programming-exercises/string/swift-string-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics