考虑以下代码:
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);
如果我在同一个characterSetWithCharactersInString:
对象NSString
上使用trimmedString
,我之前的whitespace
修剪效果会被删除..
我的问题是,
是否有可能将多个NSCharacterSet
对象用于同一NSString
???
或建议我采取其他一些方法来做到这一点,但NSString
对象应该是同一个..
答案 0 :(得分:1)
这个怎么样:
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];
答案 1 :(得分:1)
问题不在于字符集。这是因为您在第二次修剪字符串时使用aString
。您应该使用trimmedString
代替。你的代码看起来应该是,
trimmedString = [trimmedString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"string"]];