7

In my app I want to remove numbers except characters a-z from string. How can I get only characters?

Douglas
  • 36,802
  • 9
  • 76
  • 89
Saikiran Komirishetty
  • 6,525
  • 1
  • 29
  • 36

3 Answers3

26

This is the short answer which doesnt need any lengthy coding

NSString *newString = [[tempstr componentsSeparatedByCharactersInSet:
                            [[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];`

swift 3:

(tempstr.components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")

eg:

("abc123".components(separatedBy:NSCharacterSet.letters.inverted)).joined(separator: "")
Saikiran Komirishetty
  • 6,525
  • 1
  • 29
  • 36
1
NSString *stringToFilter = @"filter-me";


    NSMutableString *targetString = [NSMutableString string];


    //set of characters which are required in the string......
    NSCharacterSet *okCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];


    for(int i = 0; i < [stringToFilter length]; i++)
    {
        unichar currentChar = [stringToFilter characterAtIndex:i];
        if([okCharacterSet characterIsMember:currentChar]) 
        {
            [targetString appendFormat:@"%C", currentChar];
        }
    }


    NSLog(targetString);    


    [super viewDidLoad];
}

this was an answer given to me and works fine

Douglas
  • 36,802
  • 9
  • 76
  • 89
Ranjeet Sajwan
  • 1,925
  • 2
  • 28
  • 60
0

I found an answer: from remove-all-but-numbers-from-nsstring

NSString *originalString = @"(123) 123123 abc";

NSLog(@"%@", originalString);
NSMutableString *strippedString = [NSMutableString 
                                   stringWithCapacity:originalString.length];

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet 
                           characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];

while ([scanner isAtEnd] == NO) {
    NSString *buffer;
    if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
        [strippedString appendString:buffer];

    } else {
        [scanner setScanLocation:([scanner scanLocation] + 1)];
    }
}

NSLog(@"%@", strippedString);
Community
  • 1
  • 1
Saikiran Komirishetty
  • 6,525
  • 1
  • 29
  • 36
  • I'm no expert in xcode, but isn't there a simpler solution to perform that simple task? – Déjà vu Oct 14 '10 at 11:46
  • I'm quite surprised this hasn't been seen before but this answer has been taken word for word from stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstringst not good to copy someone else answer like that. – Popeye Jun 20 '13 at 11:16
  • sorry i didn't know about this link. Actually one of my friend gave this answer so i just copied here.. any how i will add ur link as reference to it. – Saikiran Komirishetty Jun 24 '13 at 05:32