
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 Prefix Substring from Given String in Swift
To delete the prefix substring from the given string first, we check if the given substring is present in the specified string or not using the inbuilt hasPrefix() function. Then find the index of the prefix substring using the inbuilt index() function and finally remove the prefix substring.
Input
String = "Today is cloudy day" SubString = "Today"
Output
"is cloudy day"
Here, the specified substring is found in the given string, so in the resultant string, we removed the substring from the start of the input string.
Algorithm
Step 1 ? Create a string.
Step 2 ? Create a substring.
Step 3 ? Check if the string starts with the specified substring.
Step 4 ? If yes, then calculate the index to start deleting from using the index() function. Here we pass the count of the prefix substring as the offset.
Step 5 ? Now we extract a substring using a string slicing operation from the given index till the end of the string. After that 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 prefix 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 start deleting from with the help of the index() function. Then use string slicing operation to exact the substring starting from the given index to the end of the string 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 prefixStr = "Sky" print("Original String:", str) // Check if the string starts with the // prefix substring or not if str.hasPrefix(prefixStr) { // Finding the index to start deleting from let SIndex = str.index(str.startIndex, offsetBy: prefixStr.count) // Removing the prefix substring let modifyStr = String(str[SIndex...]) print("Modified String:", modifyStr) } else { print("Substring not found") }
Output
Original String: Sky is blue Modified String: is blue
Conclusion
So this is how we can delete prefix substring from the given string. This is the most efficient method to remove a substring from the start of the input string. With some minor changes in the code, you can also remove a character from the start of the string.