stringByTrimmingCharactersInSet: is not removing characters in the middle of the string

前端 未结 6 2229
北荒
北荒 2020-12-15 06:23

I want to remove \"#\" from my string.

I have tried

 NSString *abc = [@\"A#BCD#D\" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWith         


        
相关标签:
6条回答
  • 2020-12-15 06:36

    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:@""];
    }
    
    0 讨论(0)
  • 2020-12-15 06:37

    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.

    0 讨论(0)
  • 2020-12-15 06:38

    Use below

    NSString * myString = @"A#BCD#D";
    NSString * newString = [myString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    
    0 讨论(0)
  • 2020-12-15 06:40

    Refer to the Apple Documentation about: stringByReplacingOccurrencesOfString: method in NSString

    NSString *str1=[str stringByReplacingOccurrencesOfString:@"#" withString:@""];
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-15 06:42

    You could try

    NSString *modifiedString = [yourString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    
    0 讨论(0)
  • 2020-12-15 06:50

    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:@""];
    
    0 讨论(0)
提交回复
热议问题