我将段落转换为包含许多特殊字符的单词,如
" , " . `
如何在nsstring中删除此字符并在nsstring中只获取字母
离
“新”到新//the special characters are change
答案 0 :(得分:76)
NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);
尝试这可能有助于你
答案 1 :(得分:5)
有很多方法可以解决这个问题。例如,这是使用正则表达式的解决方案。这只是一个例子。我们不知道您要删除的所有特殊字符范围。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"[,\\.`\"]"
options:0
error:NULL];
NSString *sampleString = @"The \"new\" quick brown fox, who jumped over the lazy dog.";
NSString *cleanedString = [expression stringByReplacingMatchesInString:sampleString
options:0
range:NSMakeRange(0, sampleString.length)
withTemplate:@""];
printf("cleaned = %s",[cleanedString UTF8String] );
}
return 0;
}
答案 2 :(得分:1)
@Rostyslav Druzhchenko对@MadhuP的选定答案的每个评论:
NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *escapedString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", escapedString);
这是将使用alphanumericCharacterSet
处理多个国家/地区字符集的答案。
答案 3 :(得分:0)
SWIFT接受的答案(但不是SWIFTY方式):
let notAllowedCharactersSet = NSCharacterSet(charactersInString: "ABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet
let filtered = (stringToFilter.componentsSeparatedByCharactersInSet(notAllowedCharactersSet) as NSArray).componentsJoinedByString("")
答案 4 :(得分:-1)
我确信这是一个更优雅的解决方案,但对于任何试图在Swift中执行此操作的人来说,这就是我所做的,以确保用户的电话号码中没有特殊字符。
var phone = "+1 (555) 555 - 5555"
var removeChars: NSCharacterSet = NSCharacterSet(charactersInString: "1234567890").invertedSet
var charArray = phone.componentsSeparatedByCharactersInSet(removeChars)
var placeholderString = ""
var formattedPhoneNumber: String = placeholderString.join(charArray).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
stringByTrimmingCharactersInSet
可能没有必要。