w3resource

Swift String Exercises: Create a new string of length three from a given string of odd length from its middle


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:

Flowchart: Swift String Exercises - Create a new string of length three from a given string of odd length from its middle.

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

Go to:


PREV : 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".

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.