Objective c 在目标C中格式化NSString
我有一个像748973525这样的字符串,现在我需要像748-973-525一样在目标C中格式化它使用Objective c 在目标C中格式化NSString,objective-c,nsstring,Objective C,Nsstring,我有一个像748973525这样的字符串,现在我需要像748-973-525一样在目标C中格式化它使用-[NSString substringWithRange:][/code>将原始字符串拆分为三部分,比如a、b和C,然后使用+[NSString-stringWithFormat:][/code>再次组合它们 例如: NSString *s = @"748973525"; NSString *a = [s substringWithRange: NSMakeRange(0, 3)],
-[NSString substringWithRange:][/code>将原始字符串拆分为三部分,比如a
、b
和C
,然后使用+[NSString-stringWithFormat:][/code>再次组合它们
例如:
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];
当然,这只适用于包含九个或更多字符的字符串;如果s
的长度小于9,则substringWithRange
将引发异常。解决此问题的几种方法。我们没有输入字符串的规范;但你可以采取以下措施:
#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];
}
#导入
int main(int argc,char*argv[]){
NSAutoreleasePool*p=[[NSAutoreleasePool alloc]init];
NSString*original=@“748973525”;
NSRegularExpression*exp=[NSRegularExpression regular expressionwithpattern:@“(\\d{3})(\\d{3})(\\d{3})”
选项:0错误:无];
NSString*new=[exp stringByReplacingMatchesInString:原始
选项:0范围:NSMakeRange(0,original.length)
带模板:@“$1-$2-$3”];
printf(“%s”,[new UTF8String]);
[p释放];
}
将748-973-525
打印到控制台。使用自定义的“数字格式化程序”并将“分组分隔符”设置为“-”您的字符串是否始终是数字?字符串是否始终有9位数字?@marc how删除了我关于常见问题的帖子。它充满了常见问题,是有效的,虽然它没有包含现成的代码,但如果你只是删除了部分答案,显示了一个有效的方法,将不胜感激!