Format NSString in Objective C

I have a string like 748973525 now i need to format it like 748-973-525 in Objective C

Upvotes: 1

Views: 185

Answers (3)

waldrumpus
waldrumpus

Reputation: 2590

Split your original string using -[NSString substringWithRange:] into three parts, say a, b, and c, and combine them again using +[NSString stringWithFormat:].

For example:

NSString *s = @"748973525";
NSString 
  *a = [s substringWithRange: NSMakeRange(0, 3)],
  *b = [s substringWithRange: NSMakeRange(3, 3)],
  *c = [s substringWithRange: NSMakeRange(6, 3)];
NSString *result = [NSString stringWithFormat: @"%@-%@-%@", a, b, c];

This will, of course, only work for strings with nine characters or more; if s has a length of less than nine, substringWithRange will raise an exception.

Upvotes: 1

user1804762
user1804762

Reputation:

Use a custom "Number Formatter" and set the "Grouping Separator" to "-"

Upvotes: 1

FluffulousChimp
FluffulousChimp

Reputation: 9185

Several ways of solving this. We don't have the specifications for the input string; but you could adopt the following:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    NSString *original = @"748973525";
    NSRegularExpression *exp = [NSRegularExpression regularExpressionWithPattern:@"(\\d{3})(\\d{3})(\\d{3})" 
            options:0 error:nil];
    NSString *new = [exp stringByReplacingMatchesInString:original 
            options:0 range:NSMakeRange(0,original.length) 
            withTemplate:@"$1-$2-$3"];
    printf("%s",[new UTF8String]);

    [p release];
}

Prints 748-973-525 to the console.

Upvotes: 1

Related Questions