本文介绍了从 Obj-C 中的字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Objective-C 的新手,但在其他高级语言方面有经验.我想通过删除所有非数字字符来规范化字符串.换句话说,给定输入字符串206-555-1212",标准化结果应该是2065551212".下面的代码片段有效,但考虑到我在其他语言方面的经验,这似乎有点过分.有没有更好的方法?

I'm new to Objective-C, but experienced in other higher languages. I want to normalize a string by removing all non-numeric characters. In other words given the input string "206-555-1212" the normalized result should be "2065551212". The code snippet below works, but given my experience in other languages that seems like overkill. Is there a better way to do it?

输入字符串(206) 555-1212"、206.555.1212"、206 555 1212"等也应返回相同的标准化结果.

The input strings "(206) 555-1212", "206.555.1212", "206 555 1212", etc. should also return the same normalized result.

NSString * normalize(NSString * number)
{
    NSString *normalizedNumber = @"";
    NSString *tmpString = nil;

    NSRange searchRange;
    NSRange resultRange;
    searchRange.location = 0;
    searchRange.length = number.length;

    while (0 < searchRange.length)
    {
        resultRange = [number rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]
                                        options:NSLiteralSearch
                                          range:searchRange];
        tmpString = [number substringWithRange:resultRange];
        normalizedNumber = [normalizedNumber stringByAppendingString:tmpString];
        searchRange.location = resultRange.location + resultRange.length;
        searchRange.length = number.length - searchRange.location;
    }

    return normalizedNumber;
}

推荐答案

所有这些答案都没有解决问题的删除所有非数字字符"部分.这是一个简单的方法:

All of these answers don't address the "removing all non-numeric characters" part of the question. Here's a simple way to do it:

NSString *normalize(NSString *number) {
    NSMutableCharacterSet *nonNumberCharacterSet = [NSMutableCharacterSet decimalDigitCharacterSet];
    [nonNumberCharacterSet invert];

    return [[number componentsSeparatedByCharactersInSet:nonNumberCharacterSet] componentsJoinedByString:@""];
}

这篇关于从 Obj-C 中的字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 07:48