Hi I have a string like that
NSString *str=@"1,2,3,4";
I have to remove any character from it dynamically. For example, @"3,"
.
To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.
Swift String dropLast() The dropLast() method removes the last character of the string.
To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.
Swift String dropFirst() The dropFirst() method removes the first character of the string.
NSString *str=@"1,2,3,4"; [str stringByReplacingOccurrencesOfString:@"3," withString:@""];
That will remove ALL occurrences of @"3," in str
.
If you want to remove only the first occurrence of @"3,":
NSString* str = @"1,2,3,4"; NSRange replaceRange = [str rangeOfString:@"3,"]; if (replaceRange.location != NSNotFound){ NSString* result = [str stringByReplacingCharactersInRange:replaceRange withString:@""]; }
Hope this helps.
NSString *str=@"1,2,3,4"; int numberToRemove = 4; str = [str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%d",numberToRemove] withString:@""]; str = [str stringByReplacingOccurrencesOfString:@",," withString:@","];
This will help.
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