w3resource

Swift String Exercises: Concat two given strings and return the new string

Swift String Programming: Exercise-16 with Solution

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

Pictorial Presentation:

Flowchart: Swift String Exercises - Concat two given strings and return the new string.

Sample Solution:

Swift Code:

func join_string(_ a: String, _ b: String) -> String {
    
    var str1 = a
    var str2 = b
    
    if str1.characters.last == str2.characters.first {
        str2.remove(at: str2.startIndex)
    }
    
    return str1 + str2
}

print(join_string("vwx", "xyz"))
print(join_string("vwx", "yz"))
print(join_string("vwx", ""))

Sample Output:


vwxyz
vwxyz
vwx

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 length three from a given string of odd length from its middle. The string length must be three.
Next: 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" .

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.