从NSString中删除任何非字母

时间:2014-04-29 11:28:44

标签: objective-c

我正在尝试从NSString链接中删除一些可能出现在开头和结尾的不是字母的字符。有一种简单但安全的方法吗?

示例:

NSString *link= @" www.something.com. "  //removing the `.`
NSString *link= @" [www.something.com] "  //removing the `[ ]`
NSString *link= @" www.something.com/ "  //removing the `/`

非常感谢。

2 个答案:

答案 0 :(得分:1)

请使用:

    NSCharacterSet *notAllowed = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
    NSString *resultString = [[yourString componentsSeparatedByCharactersInSet:notAllowed] componentsJoinedByString:@""];

答案 1 :(得分:1)

要从给定字符串的开头和结尾删除不需要的字符, 使用stringByTrimmingCharactersInSet

NSString *link= @" www.something.com. ";
NSCharacterSet *charset = [[NSCharacterSet letterCharacterSet] invertedSet];
NSString *stripped = [link stringByTrimmingCharactersInSet:charset];