2012-11-21 99 views
2

林用從字符串去除特殊字符的問題。我用下面的code.But力work.Please建議我更好的邏輯問題與替換特殊字符

- (NSString *)trimmedReciString:(NSString *)stringName 
{ 
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"-/:;()$&@\".,?!\'[]{}#%^*+=_|~<>€£¥•."]; 
    for (int i = 0; i < [stringName length]; i++) { 
     unichar c = [stringName characterAtIndex:i]; 
     if ([myCharSet characterIsMember:c]) { 
      NSLog(@"%@",[NSString stringWithFormat:@"%c",[stringName characterAtIndex:i]]); 
      stringName = [stringName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%c",[stringName characterAtIndex:i]] withString:@""]; 

     } 
    } 
    return stringName; 
} 

回答

8
NSString *s = @"$$$hgh$g%k&fg$$tw/-tg"; 
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"-/:;()$&@\".,?!\'[]{}#%^*+=_|~<>€£¥•."]; 
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; 
NSLog(@"String is: %@", s); 
+0

好的一個我測試此代碼輸出字符串爲:hghgkfgtwtg +1簡單的解決方案 –

+0

優雅而簡單,感謝namrata –

0

嘗試從年底開始的字符串並向後工作,而不是從前往後,因爲當前一個字符被刪除時,您可能會意外(無意)跳過字符。

3

嘗試......

NSString *unfilteredString = @"[email protected]#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet]; 
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""]; 
NSLog (@"Result: %@", resultString);