w3resource
swift Programming Exercises

Swift String Exercises: Create a new string made of 2 copies of the first 2 characters of a given string

Swift String Programming: Exercise-20 with Solution

Write a Swift program to create a new string made of 2 copies of the first 2 characters of a given string. The string may be any length.

Pictorial Presentation:

Flowchart: Swift String Exercises - Create a new string made of 2 copies of the first 2 characters of a given string.

Sample Solution:

Swift Code:

import Foundation
func two_copies(_ str1: String) -> String {
    
    if str1.characters.count == 0 {
        return ""
    } 
    else if str1.characters.count == 1 
    {
        return str1 + str1
    } 
    else 
    {
        var currentIndex = str1.index(after: str1.startIndex)
        currentIndex = str1.index(after: currentIndex)
        let res = str1.substring(to: currentIndex)
        return res + res 
    }
    
}

print(two_copies("Swift"))
print(two_copies("Online"))
print(two_copies("JS"))

Sample Output:


SwSw
OnOn
JSJS

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to create a new string of any length from a given string where the last two characters are swapped, so 'abcde' will be 'abced'.
Next: Write a Swift program to check if the first or last characters are 'a' of a given string, return the given string without those 'a' characters, and otherwise return the given string.

What is the difficulty level of this exercise?