w3resource

Swift String Exercises: Accept two strings of different length and return a string of the form short+long+short

Swift String Programming: Exercise-7 with Solution

Write a Swift program that accept two strings of different length and return a string of the form short+long+short. Two given string's length may be 0.

Pictorial Presentation:

Flowchart: Swift String Exercises - Accept two strings of different length and return a string of the form short+long+short.

Sample Solution:

Swift Code:

func combine_strings(_ str1: String, _ str2: String) -> String {
    if str1.characters.count > str2.characters.count
    {
        return str2+str1+str2
    } else 
    {
        return str1+str2+str1
    }
}

print(combine_strings("Swift", "Examples"))
print(combine_strings("", ""))
print(combine_strings("Green", "Red"))

Sample Output:


SwiftExamplesSwift

RedGreenRed

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to create a new string without the first and last character of a given string. The string length must be at least 2.
Next: Write a Swift program that accept two strings and return their concatenation, except the first char of each string. The given strings length must be at least 1.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.