w3resource

Swift Basic Programming Exercise: Remove a character at specified index of a given non-empty string

Swift Basic Programming: Exercise-6 with Solution

Write a Swift program to remove a character at specified index of a given non-empty string. The value of the specified index will be in the range 0..str.length()-1 inclusive.

Pictorial Presentation:

Swift Basic Programming Exercise: Remove a character at specified index of a given non-empty string.

Sample Solution:

Swift Code:

func remove_char(str1: String, n: Int) -> String {
    let count = str1.characters.count
    var newWord = str1
    let index = str1.index(str1.startIndex, offsetBy: n)
    if  count > 0 
    {
        newWord.remove(at: index)
    }
    return newWord
}
print(remove_char(str1: "Python", n: 1))
print(remove_char(str1: "Python", n: 0))
print(remove_char(str1: "Python", n: 4))

Sample Output:

Pthon
ython
Pythn

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to add "Is" to the front of a given string.
Next: Write a Swift program to change the first and last character of a given string.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.