0

I know it must be a very simple thing to do but I've never had to treat strings before (in Objective-C) and apparently there's not RegEx on Cocoa-Touch.

Well, the situation is:

  • I have a text field to get a value (money, such as 32.10 for instance).

The problem:

  • If the user types in a symbol such as @, /, # etc. my app will crash.

The Question: How can I treat this string to remove the symbols if there are any?

Bernardo Oliveira
  • 818
  • 1
  • 14
  • 30

3 Answers3

4

you can try this:

NSString *s = @"12.827#@584";
NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:@"/:@#"];
s = [[s componentsSeparatedByCharactersInSet: removeCharSet] componentsJoinedByString: @""];
NSLog(@"%@", s);
Gyani
  • 2,241
  • 1
  • 24
  • 38
1

You do get regex in Cocoa Touch.

Here's a good discussion of the varying degrees of regex power in iOS, the blocks example at the end should get you most of the way there.

http://volonbolon.net/post/861427732/text-handling-in-ios-4

Brandon
  • 2,900
  • 1
  • 23
  • 36
0

I understand you're trying to figure out the number included in the UITextFields's text property and assign it to a float variable.

Try using an NSScanner for this:

NSScanner* textScanner = [NSScanner localizedScannerWithString:textfield.text];
float* floatValue;
[textScanner scanFloat:&floatValue];

floatValue now contains the parsed float value of your textfield.

Marcel Hansemann
  • 1,019
  • 8
  • 11
  • Well, yeah, but what if I type something like 32@3$1"? I want to identify those symbols and remove them from my string or at least send an alert to the user saying that he can't type symbols. – Bernardo Oliveira Nov 11 '10 at 12:19
  • In that string, floatValue would be 32.00. NSScanner is the most reliable method to get number values from NSStrings. In order to check if the text field contains non-numeric characters, use [NSNumberFormatter numberFromString:]. It will return nil if the string contains more than just numbers. – Marcel Hansemann Nov 11 '10 at 12:24
  • Just tested, it is great indeed but it won't consider commas or dots, which makes the whole float thing pointless (literally). :/ Eg: 22.10 will be read as 22.00 – Bernardo Oliveira Nov 11 '10 at 12:30