stringByTrimmingCharactersInSet: is not removing characters in the middle of the string
21,419
Solution 1
You could try
NSString *modifiedString = [yourString stringByReplacingOccurrencesOfString:@"#" withString:@""];
Solution 2
stringByTrimmingCharactersInSet
removes characters from the beginning and end of your string, not from any place in it
For your purpose use stringByReplacingOccurrencesOfString:withString:
method as others pointed.
Solution 3
I wrote a category of NSString
for that:
- (NSString *)stringByReplaceCharacterSet:(NSCharacterSet *)characterset withString:(NSString *)string {
NSString *result = self;
NSRange range = [result rangeOfCharacterFromSet:characterset];
while (range.location != NSNotFound) {
result = [result stringByReplacingCharactersInRange:range withString:string];
range = [result rangeOfCharacterFromSet:characterset];
}
return result;
}
You can use it like this:
NSCharacterSet *funnyCharset = [NSCharacterSet characterSetWithCharactersInString:@"#"];
NSString *newString = [string stringByReplaceCharacterSet:funnyCharset withString:@""];
Solution 4
I previously had a relatively complicated recursive answer for this (see edit history of this answer if you'd like to see that answer), but then I found a pretty simple one liner:
- (NSString *)stringByRemovingCharactersInSet:(NSCharacterSet *)characterSet {
return [[self componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
}
Solution 5
Refer to the Apple Documentation about: stringByReplacingOccurrencesOfString: method in NSString
NSString *str1=[str stringByReplacingOccurrencesOfString:@"#" withString:@""];
Hope this helps.
Related videos on Youtube
Author by
Sookcha
Updated on July 13, 2020Comments
-
Sookcha almost 4 years
I want to remove "#" from my string.
I have tried
NSString *abc = [@"A#BCD#D" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
But it still shows the string as "A#BCD#D"
What could be wrong?
-
ArtOfWarfare over 9 years+1, although I dislike the redundancy caused by using a
while
loop, so I wrote a method which uses recursion instead (do-while
probably could have also removed the redundancies): stackoverflow.com/a/26152034/901641 -
manecosta about 9 yearstook me quite a while to figure why xcode wasn't accepting it :) thanks for the answer by the way.
-
CommaToast about 8 yearsThen why the heck isn't it called "stringByTrimmingCharactersInSetJustFromTheVeryEndOrVeryBeginning"...
-
Vladimir about 8 yearsI guess trim implies that, but I am not a native english speaker :)