如何将字符串格式化为信用卡格式

时间:2021-12-13 18:24:26

What is the easiest way to format a string "1234567890123456789" to "1234 5678 9012 3456 789" in IOS?

在IOS中将字符串“1234567890123456789”格式化为“1234 5678 9012 3456 789”的最简单方法是什么?

5 个解决方案

#1


3  

Try this:

-(NSString *) correctString:(NSString *) anyStr {

  NSMutableString *str=[NSMutableString stringWithString:anyStr];
int indx=4;
while (indx<str.length) {
    [str insertString:@" " atIndex:indx];
    indx +=5;
}
anyStr=str;
return anyStr;
}

#2


3  

For that particular format, you could do something like the following, which extracts the individual substrings:

对于该特定格式,您可以执行以下操作,提取单个子字符串:

NSString *string = @"1234567890123456789";
NSMutableArray *array = [NSMutableArray array];
for (NSInteger i = 0; i < [string length]; i += 4)
    [array addObject:[string substringWithRange:NSMakeRange(i, MIN(4, [string length] - i))]];
NSString *result = [array componentsJoinedByString:@" "];

The thing is, not all credit cards conform to the xxxx xxxx xxxx xxxx format. E.g., Amex uses a xxxx xxxxxx xxxxx format. You really should look at the first digits of the card, determine the type of card, and format it accordingly.

问题是,并非所有信用卡都符合xxxx xxxx xxxx xxxx格式。例如,Amex使用xxxx xxxxxx xxxxx格式。你真的应该看看卡的第一个数字,确定卡的类型,并相应地格式化。


You asked if you could do it with a regular expression. Consider this regex:

你问过你是否可以用正则表达式来做。考虑这个正则表达式:

NSString *result = [string stringByReplacingOccurrencesOfString:@"^[\\s-]*([0-9]{4})[\\s-]*([0-9]{4})[\\s-]*([0-9]{4})[\\s-]*([0-9]{4})[\\s-]*([0-9]{3})[\\s-]*$"
                                                     withString:@"$1 $2 $3 $4 $5"
                                                        options:NSRegularExpressionSearch
                                                          range:NSMakeRange(0, [string length])];

That will convert any of the following:

这将转换以下任何一项:

@"1234567890123456789"
@"1234-5678-9012-3456-789"
@"  1234567890123456789  "

into:

@"1234 5678 9012 3456 789"

While you could use regular expression, it's sufficiently opaque that I wouldn't particularly advise it. But it can be done.

虽然你可以使用正则表达式,但它是不够透明的,我不会特别建议它。但这是可以完成的。

#3


0  

I wrote code.

我写了代码。

NSMutableString *string = @"1234567890123456789"; 

NSInteger *ip = 4;

for (NSInteger i = 0; i*4 < [string length] ; i++)
{
    [string insertString:@" " atIndex:ip];
    ip = ip+5;
}

#4


0  

I propose to use NSString category. In not ARC just add autorelease after self copy. My variant will not add spaces after last digits quarter if it is not nescessary. Applicable to use in UITextField.

我建议使用NSString类。在ARC中,只需在自我复制后添加自动释放。如果不是必要的话,我的变体将不会在最后一个数字季度之后添加空格。适用于UITextField。

- (NSString *)creditCardNumberFormatedString {
    NSString *string = [self copy];
    NSUInteger length = string.length;
    if (length >= 17) {
        string = [string substringToIndex:16];
        length = 16;
    }

    BOOL isSpaceRequired = YES;
    if (length == 4) {
        isSpaceRequired = NO;

    }

    NSString *newString = [NSString new];
    while (string.length > 0) {
        NSString *subString = [string substringToIndex:MIN(string.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4 && isSpaceRequired) {
            newString = [newString stringByAppendingString:@" "];
        }

        string = [string substringFromIndex:MIN(string.length, 4)];
        if (string.length <= 4) {
            isSpaceRequired = NO;
        }
    }

    return newString;
}

#5


0  

Here is a Swift extension:

这是一个Swift扩展:

extension String {
    var pairs: [String] {
        var result: [String] = []
        let chars = Array(characters)
        for index in 0.stride(to: chars.count, by: 4) {
            result.append(String(chars[index..<min(index+4, chars.count)]))
        }
        return result
    }
}

To use:

let string : String = "1234567890123456789"
let finalString = string.pairs.joinWithSeparator(" ") //1234 5678 9012 3456 789
print(finalString)

For Swift 3:

对于Swift 3:

extension String {
    var pairs: [String] {
        var result: [String] = []
        let chars = Array(characters)
        for index in stride(from: 0, to: chars.count, by: 4){
            result.append(String(chars[index..<min(index+4, chars.count)]))
        }
        return result
    }
}

#1


3  

Try this:

-(NSString *) correctString:(NSString *) anyStr {

  NSMutableString *str=[NSMutableString stringWithString:anyStr];
int indx=4;
while (indx<str.length) {
    [str insertString:@" " atIndex:indx];
    indx +=5;
}
anyStr=str;
return anyStr;
}

#2


3  

For that particular format, you could do something like the following, which extracts the individual substrings:

对于该特定格式,您可以执行以下操作,提取单个子字符串:

NSString *string = @"1234567890123456789";
NSMutableArray *array = [NSMutableArray array];
for (NSInteger i = 0; i < [string length]; i += 4)
    [array addObject:[string substringWithRange:NSMakeRange(i, MIN(4, [string length] - i))]];
NSString *result = [array componentsJoinedByString:@" "];

The thing is, not all credit cards conform to the xxxx xxxx xxxx xxxx format. E.g., Amex uses a xxxx xxxxxx xxxxx format. You really should look at the first digits of the card, determine the type of card, and format it accordingly.

问题是,并非所有信用卡都符合xxxx xxxx xxxx xxxx格式。例如,Amex使用xxxx xxxxxx xxxxx格式。你真的应该看看卡的第一个数字,确定卡的类型,并相应地格式化。


You asked if you could do it with a regular expression. Consider this regex:

你问过你是否可以用正则表达式来做。考虑这个正则表达式:

NSString *result = [string stringByReplacingOccurrencesOfString:@"^[\\s-]*([0-9]{4})[\\s-]*([0-9]{4})[\\s-]*([0-9]{4})[\\s-]*([0-9]{4})[\\s-]*([0-9]{3})[\\s-]*$"
                                                     withString:@"$1 $2 $3 $4 $5"
                                                        options:NSRegularExpressionSearch
                                                          range:NSMakeRange(0, [string length])];

That will convert any of the following:

这将转换以下任何一项:

@"1234567890123456789"
@"1234-5678-9012-3456-789"
@"  1234567890123456789  "

into:

@"1234 5678 9012 3456 789"

While you could use regular expression, it's sufficiently opaque that I wouldn't particularly advise it. But it can be done.

虽然你可以使用正则表达式,但它是不够透明的,我不会特别建议它。但这是可以完成的。

#3


0  

I wrote code.

我写了代码。

NSMutableString *string = @"1234567890123456789"; 

NSInteger *ip = 4;

for (NSInteger i = 0; i*4 < [string length] ; i++)
{
    [string insertString:@" " atIndex:ip];
    ip = ip+5;
}

#4


0  

I propose to use NSString category. In not ARC just add autorelease after self copy. My variant will not add spaces after last digits quarter if it is not nescessary. Applicable to use in UITextField.

我建议使用NSString类。在ARC中,只需在自我复制后添加自动释放。如果不是必要的话,我的变体将不会在最后一个数字季度之后添加空格。适用于UITextField。

- (NSString *)creditCardNumberFormatedString {
    NSString *string = [self copy];
    NSUInteger length = string.length;
    if (length >= 17) {
        string = [string substringToIndex:16];
        length = 16;
    }

    BOOL isSpaceRequired = YES;
    if (length == 4) {
        isSpaceRequired = NO;

    }

    NSString *newString = [NSString new];
    while (string.length > 0) {
        NSString *subString = [string substringToIndex:MIN(string.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4 && isSpaceRequired) {
            newString = [newString stringByAppendingString:@" "];
        }

        string = [string substringFromIndex:MIN(string.length, 4)];
        if (string.length <= 4) {
            isSpaceRequired = NO;
        }
    }

    return newString;
}

#5


0  

Here is a Swift extension:

这是一个Swift扩展:

extension String {
    var pairs: [String] {
        var result: [String] = []
        let chars = Array(characters)
        for index in 0.stride(to: chars.count, by: 4) {
            result.append(String(chars[index..<min(index+4, chars.count)]))
        }
        return result
    }
}

To use:

let string : String = "1234567890123456789"
let finalString = string.pairs.joinWithSeparator(" ") //1234 5678 9012 3456 789
print(finalString)

For Swift 3:

对于Swift 3:

extension String {
    var pairs: [String] {
        var result: [String] = []
        let chars = Array(characters)
        for index in stride(from: 0, to: chars.count, by: 4){
            result.append(String(chars[index..<min(index+4, chars.count)]))
        }
        return result
    }
}