How to use NSNumberFormatter to insert blank space to NSString? - ios

I want to write a UITextField that can auto format a number to bank number.
For example: Input 1234567890098765 will be automatically displayed as 1234 5678 9009 8765.
I'll use textFieldDelegate to do it, but I don't know how to use NSNumberFormatter.
How can I do it?

Using NSNumberFormatter is simple.
NSNumber *number = [NSNumber numberWithLongLong:1234567890098765];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setUsesGroupingSeparator:YES];
[formatter setGroupingSize:3];
// [formatter setGroupingSeparator:#"\u00a0"];
NSString *string = [formatter stringFromNumber:number];
I deliberately commented the line that sets the formatter's grouping separator as it may be better to use the default one, which is provided by the user's locale (e.g. , in the USA, . in Germany and ' in Switzerland). Also please note that iOS doesn't use a space as a separator but a non-breaking space (U+00A0).

Try this :-
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *text = [textField text];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789\b"];
string = [string stringByReplacingOccurrencesOfString:#" " withString:#""];
if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
return NO;
}
text = [text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *newString = #"";
while (text.length > 0) {
NSString *subString = [text substringToIndex:MIN(text.length, 4)];
newString = [newString stringByAppendingString:subString];
if (subString.length == 4) {
newString = [newString stringByAppendingString:#" "];
}
text = [text substringFromIndex:MIN(text.length, 4)];
}
newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
if (newString.length >= 20) {
return NO;
}
[textField setText:newString];
return NO;
}
Hope this helps you..

i have a c++ solution, maybe you can change your string to cstring and then change back
char s[50]={'\0'},ch[99]={'\0'};
int i,j,k,len;
printf("input a string:\n");
scanf("%s",s);
len=strlen(s);
k=0;
for(i=0;i<len;i+=4)
{
for(j=0;j<4;j++)
{
*(ch+k)=*(s+i+j);
k++;
}
*(ch+k)=' ';
k++;
}
printf("%s\n",ch);

Related

How do I format a UITextfield's text that happens to be a telephone number, in american style?

Let's say I have this number 1234567890
and I want it in this format (xxx) xxx-xxxx
So on the display I'd like it to display as (123) 456-7890
How would I achieve this?
Would I need to use some sort of regex on the textfield?
Thanks for your time
In case you are using Swift:
let phoneNum = activity["phoneNumber"] as String
let digits = NSCharacterSet.decimalDigitCharacterSet().invertedSet as NSCharacterSet
let filtered1 = phoneNum.componentsSeparatedByCharactersInSet(digits) as NSArray
let filtered = filtered1.componentsJoinedByString("") as NSString
if filtered.length == 11 {
let formatted = NSString(format: "(%#) %#-%#", filtered.substringWithRange(NSMakeRange(1, 3)), filtered.substringWithRange(NSMakeRange(4, 3)), filtered.substringWithRange(NSMakeRange(7, 4))) as NSString
phoneNumberField.text = formatted
} else if filtered.length == 10 {
let formatted = NSString(format: "(%#) %#-%#", filtered.substringWithRange(NSMakeRange(0, 3)), filtered.substringWithRange(NSMakeRange(3, 3)), filtered.substringWithRange(NSMakeRange(6, 4))) as NSString
phoneNumberField.text = formatted
}
Try something like this:
NSCharacterSet *digits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString *filtered = [[[textField text] componentsSeparatedByCharactersInSet: digits] componentsJoinedByString: #""];
if ([filtered length] == 11) {
NSString *formatted = [NSString stringWithFormat: #"(%#) %#-%#", [filtered substringWithRange: NSMakeRange(1, 3)], [filtered substringWithRange: NSMakeRange(4, 3)], [filtered substringWithRange: NSMakeRange(7, 4)]];
[textField setText: formatted];
} else if ([filtered length] == 10) {
NSString *formatted = [NSString stringWithFormat: #"(%#) %#-%#", [filtered substringWithRange: NSMakeRange(0, 3)], [filtered substringWithRange: NSMakeRange(3, 3)], [filtered substringWithRange: NSMakeRange(6, 4)]];
[textField setText: formatted];
}
Try using RMPhoneFormat.
From GitHub page: "RMPhoneFormat provides a simple to use class for formatting and validating phone numbers in iOS apps. The formatting should replicate what you would see in the Contacts app for the same phone number."

Remove all non-numeric characters from an NSString, keeping spaces

I am trying to remove all of the non-numeric characters from an NSString, but I also need to keep the spaces. Here is what I have been using.
NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];
If I give it a NSString of Test 333 9599 999 It will return 3339599999 but I need to keep the spaces in.
How can I do this?
Easily done by creating a character set of characters you want to keep and using invertedSet to create an "all others" set. Then split the string into an array separated by any characters in this set and reassemble the string again. Sounds complicated but very simple to implement:
NSCharacterSet *setToRemove =
[NSCharacterSet characterSetWithCharactersInString:#"0123456789 "];
NSCharacterSet *setToKeep = [setToRemove invertedSet];
NSString *newString =
[[someString componentsSeparatedByCharactersInSet:setToKeep]
componentsJoinedByString:#""];
result: 333 9599 99
You could alter your first regex to include a space after the 9:
In swift:
var str = "test Test 333 9599 999";
val strippedStr = str.stringByReplacingOccurrencesOfString("[^0-9 ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
// strippedStr = " 33 9599 999"
While this leaves the leading space, you could apply a whitespace trimming to deal with that:
strippedStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// strippedStr = "33 9599 999"
// Our test string
NSString* _bbox = #"Test 333 9599 999";
// Remove everything except numeric digits and spaces
NSString *strippedBbox = [_bbox stringByReplacingOccurrencesOfString:#"[^\\d ]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [_bbox length])];
// (Optional) Trim spaces on either end, but keep spaces in the middle
strippedBbox = [strippedBbox stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// Print result
NSLog(#"%#", strippedBbox);
This prints 333 9599 999, which I think is what you're after. It also removes non numeric characters that may be in the middle of the string, such as parentheses.
For Swift 3.0.1 folks
var str = "1 3 6 .599.188-99 "
str.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression, range: nil)
Output: "13659918899"
This also trim spaces from string
try using NSScanner
NSString *originalString = #"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789 "];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString); // "123123123"
NSMutableString strippedBbox = [_bbox mutableCopy];
NSCharacterSet* charSet = [NSCharacterSet characterSetWithCharactersInString:#"1234567890 "].invertedSet;
NSUInteger start = 0;
NSUInteger length = _bbox.length;
while(length > 0)
{
NSRange range = [strippedBbox rangeOfCharacterFromSet:charSet options:0 range:NSMakeRange(start, length)];
if(range.location == NSNotFound)
{
break;
}
start += (range.location + range.length);
length -= range.length;
[strippedBbox replaceCharactersInRange:range withString:#""];
}
In brief, you can use NSCharacterSet to examine only those chars that are interesting to you and ignore the rest.
- (void) stripper {
NSString *inString = #"A1 B2 C3 D4";
NSString *outString = #"";
for (int i = 0; i < inString.length; i++) {
if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:[inString characterAtIndex:i]] || [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[inString characterAtIndex:i]]) {
outString = [outString stringByAppendingString:[NSString stringWithFormat:#"%c",[inString characterAtIndex:i]]];
}
}
}

How to insert a string automatically while user editing UITEXTFIELD

I want to my uitextfield be like XXX.XXX.XXX/XX at the end of typing.
To limit the lenght I use this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == _cpfField) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
} else{
return YES;
}
}
The problem is how to insert the "." and "/" while user still editing it.
The following code should do the following:
Limit the number of characters that can be typed/pasted into the text field
Automatically add periods and slashes at the appropriate locations
Prevent issues from the user copy/pasting a string that already has the necessary periods/slashes
That said, there is almost certainly more efficient ways to do this; but if you're not concerned about code length it'll do the trick just fine.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *text = textField.text;
// If we're trying to add more than the max amount of characters, don't allow it
if ([text length] == 14 && range.location > 13) {
return NO;
}
// First lets add the whole string we're going for
text = [text stringByReplacingCharactersInRange:range withString:string];
// Now remove spaces, periods, and slashes (since we'll add these automatically in a minute)
text = [text stringByReplacingOccurrencesOfString:#" " withString:#""];
text = [text stringByReplacingOccurrencesOfString:#"." withString:#""];
text = [text stringByReplacingOccurrencesOfString:#"/" withString:#""];
// We need to use an NSMutableString to do insertString calls in a moment
NSMutableString *mutableText = [text mutableCopy];
// Every 4th char will be a '.', but we don't want to check more than the first 8 characters
for (NSUInteger i = 3; i < mutableText.length && i < 8; i += 4) {
[mutableText insertString:#"." atIndex:i];
}
// If the text is more than 11 characters, we also want to insert a '/' at the 11th character index
if (mutableText.length > 11) {
[mutableText insertString:#"/" atIndex:11];
}
// lets set text to our new string
text = mutableText;
// Now, lets check if we need to cut off extra characters (like if the person pasted a too-long string)
if (text.length > 14) {
text = [text stringByReplacingCharactersInRange:NSMakeRange(14, mutableText.length-14) withString:#""];
}
// Finally, set the textfield to our newly modified string!
textField.text = text;
return NO;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *text = textField.text;
text = [text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:#"." withString:#""];
// Do your length checking here
NSMutableString *mutableText = [text mutableCopy];
// Every 4th char will be a .
for (NSUInteger i = 3; i < mutableText.length; i += 4) {
[mutableText insertString:#"." atIndex:i];
}
textField.text = mutableText;
return NO;
}
UK National Insurance Number Text Field
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == _txtNationalInsuranceNumber) {
NSString *text = textField.text;
// If we're trying to add more than the max amount of characters, don't allow it
if ([text length] == 13 && range.location > 12) {
return NO;
}
// First lets add the whole string we're going for
text = [text stringByReplacingCharactersInRange:range withString:string];
// Now remove spaces, periods, and slashes (since we'll add these automatically in a minute)
text = [text stringByReplacingOccurrencesOfString:#" " withString:#""];
// We need to use an NSMutableString to do insertString calls in a moment
NSMutableString *mutableText = [text mutableCopy];
// Every 4th char will be a '.', but we don't want to check more than the first 8 characters
for (NSUInteger i = 2; i < mutableText.length && i < 10; i += 3) {
[mutableText insertString:#" " atIndex:i];
}
// If the text is more than 11 characters, we also want to insert a '/' at the 11th character index
if (mutableText.length > 11) {
[mutableText insertString:#" " atIndex:11];
}
// lets set text to our new string
text = mutableText;
// Now, lets check if we need to cut off extra characters (like if the person pasted a too-long string)
if (text.length > 14) {
text = [text stringByReplacingCharactersInRange:NSMakeRange(14, mutableText.length-14) withString:#""];
}
// Finally, set the textfield to our newly modified string!
textField.text = text;
return NO;
}
else
{
return YES;
}
}

How to convert a currency string to number

I have the following string:
R$1.234.567,89
I need it to look like: 1.234.567.89
How can i do this?
This is what i tried:
NSString* cleanedString = [myString stringByReplacingOccurrencesOfString:#"." withString:#""];
cleanedString = [[cleanedString stringByReplacingOccurrencesOfString:#"," withString:#"."]
stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]];
It works, but I think there must be a better way. Suggestions?
If your number always after $, but you got more characters before it, you can make it like this:
NSString* test = #"R$1.234.567,89";
NSString* test2 = #"TESTERR$1.234.567,89";
NSString* test3 = #"HEllo123344R$1.234.567,89";
NSLog(#"%#",[self makeCleanedText:test]);
NSLog(#"%#",[self makeCleanedText:test2]);
NSLog(#"%#",[self makeCleanedText:test3]);
method is:
- (NSString*) makeCleanedText:(NSString*) text{
int indexFrom = 0;
for (NSInteger charIdx=0; charIdx<[text length]; charIdx++)
if ( '$' == [text characterAtIndex:charIdx])
indexFrom = charIdx + 1;
text = [text stringByReplacingOccurrencesOfString:#"," withString:#"."];
return [text substringFromIndex:indexFrom];
}
result is:
2013-10-20 22:35:39.726 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.728 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.731 test[40546:60b] 1.234.567.89
If you just want to remove the first two characters from your string you can do this
NSString *cleanedString = [myString substringFromIndex:2];

how to validation and format input string to 1234567890 to 123-456-7890

I have to format input string as phone number.For i am using
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
if (string.length==3||string.length==7) {
filtered =[filtered stringByAppendingString:#"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
here
#define NUMBERS_ONLY #"1234567890-"
#define CHARACTER_LIMIT 12
but its not editing back.
Please give some ideas
The method you're using is a UITextFieldDelegate method that determines whether or not to allow a change to the text field - given the range and replacement text, should the change be made (YES or NO).
You're trying to format a string while it is being typed - for this you'll also need to update the value of the textField.text property. This could be done in the same method while returning a "NO" afterwards.
For validation,
- (BOOL) isValidPhoneNumber
{
NSString *numberRegex = #"(([+]{1}|[0]{2}){0,1}+[0]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",numberRegex];
return [numberTest evaluateWithObject:self.inputString];
}
You can use this for formatting the string,
self.inputString = #"1234567890"
NSArray *stringComponents = [NSArray arrayWithObjects:[self.inputString substringWithRange:NSMakeRange(0, 3)],
[self.inputString substringWithRange:NSMakeRange(3, 3)],
[self.inputString substringWithRange:NSMakeRange(6, [self.inputString length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"%#-%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];

Resources