Mask for CNPJ in Objective C

Asked

Viewed 602 times

1

I’m trying to put a mask on a string that’s a CNPJ. I get a string with size 14 and tried this way to put the mask:

 NSString *cnpj = [NSString stringWithFormat:@"%@.%@.%@/%@-%@", 
 self.codCnpj substringWithRange:NSMakeRange(11, 2)], 
 [self.codCnpj substringWithRange:NSMakeRange(8, 3)], 
 [self.codCnpj substringWithRange:NSMakeRange(5, 3)],     
 [self.codCnpj substringWithRange:NSMakeRange(1, 4)],
 [self.codCnpj substringWithRange:NSMakeRange(0, 2)]];

Well, that’s not working out at all.. Some values repeat themselves and others are not shown. Does anyone have any suggestions for improvement or a simpler way to do this?

  • 3

    I will reply here in the comment because I do not have much time for a giant response as the guys here "require". If you answer with something short, you usually get a bunch of negative trolls.. so without further ado: https://github.com/fjcaetano/NStringMask In google I searched for "objective c input Mask"

  • Thank you for the reply @Danielomine . As it was only this situation that would need to have a mask, I ended up finding another solution using only the same substringWithRange.

1 answer

2


I will answer myself because I found a way only using substring. What was wrong was the order of the indices. So follow my solution:

NSString *finalCnpj = [NSString stringWithFormat:@"%@.%@.%@/%@-%@", 
[self.cnpj substringWithRange:NSMakeRange(0, 2)], 
[self.cnpj substringWithRange:NSMakeRange(2, 3)], 
[self.cnpj substringWithRange:NSMakeRange(5, 3)], 
[self.cnpj substringWithRange:NSMakeRange(8, 4)], 
[self.cnpj substringWithRange:NSMakeRange(12, 2)]];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.