我正在将段落转换为包含许多特殊字符的单词,例如
" , " . `
如何删除 nsstring 中的这些字符并仅获取 nsstring 中的字母
前“新”到新//the special characters are change
我正在将段落转换为包含许多特殊字符的单词,例如
" , " . `
如何删除 nsstring 中的这些字符并仅获取 nsstring 中的字母
前“新”到新//the special characters are change
NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);
试试这个它可以帮助你
有很多方法可以处理这个问题。例如,这是一个使用正则表达式的解决方案。这只是一个例子。我们不知道您要删除的所有特殊字符范围。
#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;
}
根据@Rostyslav Druzhchenko 对@MadhuP 所选答案的评论:
NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
NSString *escapedString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", escapedString);
这是alphanumericCharacterSet
用于处理多个国家字符集的答案。
SWIFT 接受的答案(但不是 SWIFTY 方式):
let notAllowedCharactersSet = NSCharacterSet(charactersInString: "ABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet
let filtered = (stringToFilter.componentsSeparatedByCharactersInSet(notAllowedCharactersSet) as NSArray).componentsJoinedByString("")
我确信有一个更优雅的解决方案,但对于任何试图在 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
可能没有必要。