w3resource

Swift Basic Programming Exercise: Create a string made of every other char starting with the first from a given string

Swift Basic Programming: Exercise-21 with Solution

Write a Swift program to create a string made of every other char starting with the first from a given string. So "Python" will return "Pto".

Pictorial Presentation:

Swift Basic Programming Exercise: Create a string made of every other char starting with the first from a given string.

Sample Solution:

Swift Code:

func new_string(_ input: String) -> String {
    var str1 = ""
    let chars = input.characters
    
    for (index, char) in chars.enumerated() {
        if index % 2 == 0 {
            str1.append(char)
        }
    }
    
    return str1
}
print(new_string("Python"))
print(new_string("Swift"))
print(new_string("Ab"))

Sample Output:

Pto
Sit
A

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to check if the first instance of "a" in a given string is immediately followed by another "a".
Next: Write a Swift program to create a Swift program to count the number of 7's in a given array of integers.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/swift-programming-exercises/basic/swift-basic-exercise-21.php