a string such as ! !! yuahl! !
, I want delete !
and , when I code like this
for index in InputName.characters.indices {
if String(InputName[index]) == "" || InputName.substringToIndex(index) == "!" {
InputName.removeAtIndex(index)
}
}
have this error " fatal error: subscript: subRange extends past String end ", how should I do? THX :D
How to Remove Specific Characters from a String in Swift? To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll (where:) method on this string str, with the predicate that if the specific characters contain this character in the String.
To remove a specific object from an element in swift, we can use multiple ways of doing it. Let’s see this in the playground with help of an example. First, let’s create an array of String. We’ll do it with the following methods as shown below: Method 1 − Using the filter method of the array.
The remove () method removes a character in the string at the specified position. Here, string is an object of the String class. The remove () method takes only one parameter. var message = "Hello, World!" print("Before Removing:", message) // position of the character to remove var i = message.index (message.startIndex, offsetBy: 12)
where str1 is the string and i is the index. i is of type String.Index. remove () method removes character at index i in the string str1 and returns this removed character. In the following program, we will take a string str1, and remove the character at position i=6 using String.remove () method.
Swift 5+
let myString = "aaaaaaaabbbb"
let replaced = myString.replacingOccurrences(of: "bbbb", with: "") // "aaaaaaaa"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With