【问题标题】:Is there any possibility to use more than one NSCharacterSet Object for the same NSString?是否有可能为同一个 NSString 使用多个 NSCharacterSet 对象?
【发布时间】:2011-09-14 13:04:09
【问题描述】:

考虑这段代码:

NSString *aString = @"\tThis is a sample string";
NSString *trimmedString = [aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"The trimmed string: %@",trimmedString);
trimmedString = [aString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"string"]];
NSLog(@"The trimmed string: %@",trimmedString);

如果我在同一个NSString 对象trimmedString 上使用characterSetWithCharactersInString:,我之前的whitespace 修剪效果将被删除..

我的问题是,

有没有可能对同一个NSString 使用多个NSCharacterSet 对象??? 或者请给我一些其他的方法来做到这一点,但NSString 对象应该是一个相同的..

【问题讨论】:

    标签: iphone objective-c ios nsstring nscharacterset


    【解决方案1】:

    问题不在于字符集。这是因为您在第二次修剪字符串时使用了aString。您应该改用trimmedString。你的代码应该是这样的,

    trimmedString = [trimmedString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"string"]];
    

    【讨论】:

    • @EmptyStack:是的,对..我在第二行用'trimmedString'替换了'aString'..它的工作..谢谢你..
    【解决方案2】:

    这个呢:

    NSString *aString = @"\tThis is a sample string";
    NSMutableCharacterSet *customSet = [[NSMutableCharacterSet alloc] init];
    [customSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
    [customSet addCharactersInString:@"string"];
    NSString *trimmedString = [aString stringByTrimmingCharactersInSet:customSet];
    [customSet release];
    

    【讨论】:

    • Nekto 不错.. 但是告诉 EmptyStack 更简单.. 感谢您的回答 :)
    • 我只问了你的问题Is there any possibility to use more than one NSCharacterSet object to the same NSString???。我没有在您的代码中搜索错误 =)
    • +1,他应该更喜欢这种方法。当他需要使用更多字符集时,这将非常有用。
    猜你喜欢
    • 2014-02-13
    • 2014-09-07
    • 1970-01-01
    • 2020-05-30
    • 2021-10-04
    • 2012-03-21
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多