
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete Suffix Substring from Given String in Swift
To delete the suffix substring from the given string first, we check if the given substring is present in the specified string or not using the inbuilt hasSuffix() function. Then find the index of the suffix substring using the inbuilt index() function and finally remove the suffix substring.
Input
String = "Siya love cooking" Substring = "cooking"
Output
"Siya love"
Here, the specified substring is found in the given string, so in the resultant string, we removed the substring from the end of the input string.
Algorithm
Step 1 ? Create a string.
Step 2 ? Create a substring.
Step 3 ? Check if the string ends with the specified substring.
Step 4 ? If yes, then calculate the index to stop deleting using the index() function. Here we pass a negative count of the suffix substring as the offset to indicate the position to stop deleting.
Step 5 ? Now we extract a substring using a string slicing operation from the input string but does not include the specified index. And convert the return result into a string using the String() function.
Step 6 ? Print the output.
Example
In the following Swift program, we will delete the suffix substring from the given string. So create a string and the substring. Then check if the specified substring is present in the given string or not. If yes, then find the index to stop deleting with the help of the index() function. Then use string slicing to exact the substring starting from the input string but not including the specified index, then we will create a new string using String() initializer with the extracted substring. And finally, we will print the output. If the substring does not present, then return "string not found".
import Foundation import Glibc let str = "Sky is blue" let suffixStr = " blue" print("Original String:", str) // Checking if the string ends with the // suffix substring or not if str.hasSuffix(suffixStr) { // Find the index to stop deleting at let LIndex = str.index(str.endIndex, offsetBy: -suffixStr.count) // Removing the suffix substring let modifyStr = String(str[..<LIndex]) print("Modified String:", modifyStr) } else { print("String not found") }
Output
Original String: Sky is blue Modified String: Sky is
Conclusion
So this is how we can delete suffix substring from the given string. This is the most efficient method to remove a substring from the end of the input string. With some minor changes in the code, you can also remove a character from the end of the string.