Swift Program to remove the last specified character from the string


To remove the last specified character from the string Swift provide a pre-defined remove(at:) function. This function removes a character from the specified position or index.

Input

String = “Today is cloudy day”
Character = “o”

Output

“Today is cludy day”

Where character “o” appears two times in the input string so using the remove(at:) function we removed the last appearance of the “o” character from the string. Hence the output string is “Today is cludy day”.

Syntax

Str.remove(at:Idx)

Where Str is the input string and idx is the valid position/index of the specified character to remove.

Algorithm

  • Step 1 − Create a string.

  • Step 2 − Create a variable of character type and store the character whose last presence is going to remove.

  • Step 3 − Now Check if the specified character is present in the input string or not.

  • Step 4 − If yes, then find the last index of the specified character using the lastIndex() function.

  • Step 5 − Then remove the last occurrence of the specified character from the input string using the remove() function and store the result in a new string.

  • Step 6 − Print the modified string.

  • Step 7 − If the specified character is not found, then print “Character not found”.

Example

In the following Swift program, we will remove the last specified character from the string. So first create a string and a character which we want to remove. Then check if the specified character is present or not in the input string. If yes, then we will find the index of the last occurrence of the specified character and then remove that character from the string using the remove() function and finally display the updated string.

import Foundation
import Glibc

let sentence = "Tutorials Point" 
let char: Character = "t" 

print("Original String:", sentence)

// Finding the last index of the character to remove
if let lIndex = sentence.lastIndex(of: char) {
   // Remove the character at the last index
   var modifyStr = sentence
   modifyStr.remove(at: lIndex)
    
   print("Modified String:", modifyStr)
} else {
   // Character not found in the string
   print("Character not found. Try Again")
}

Output

Original String: Tutorials Point
Modified String: Tutorials Poin

Conclusion

So this is how we can remove the last specified character from the string. Using the remove() method you can also remove any character from the string but for that, you need to specify the index of that character. If the index is not a valid index, then this method will throw an exception.

Updated on: 10-May-2023

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements