xcode NSString 为每 4 个字符附加空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26116232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSString append WhiteSpace for every 4 Character
提问by Harish
I have a string like @"1234123412341234", i need to append space between every 4 chars like.
我有一个像@"1234123412341234"这样的字符串,我需要在每 4 个字符之间添加空格。
@"1234 1234 1234 1234"
i.e, I need a NSString
like Visa Card Type. I have tried like this but i didn't get my result.
即,我需要一个NSString
类似的 Visa 卡类型。我试过这样,但我没有得到我的结果。
-(void)resetCardNumberAsVisa:(NSString*)aNumber
{
NSMutableString *s = [aNumber mutableCopy];
for(int p=0; p<[s length]; p++)
{
if(p%4==0)
{
[s insertString:@" " atIndex:p];
}
}
NSLog(@"%@",s);
}
回答by Nikolai Ruhe
Here's a unicode aware implementation as a category on NSString
:
这是一个 unicode 感知实现作为一个类别NSString
:
@interface NSString (NRStringFormatting)
- (NSString *)stringByFormattingAsCreditCardNumber;
@end
@implementation NSString (NRStringFormatting)
- (NSString *)stringByFormattingAsCreditCardNumber
{
NSMutableString *result = [NSMutableString string];
__block NSInteger count = -1;
[self enumerateSubstringsInRange:(NSRange){0, [self length]}
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([substring rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound)
return;
count += 1;
if (count == 4) {
[result appendString:@" "];
count = 0;
}
[result appendString:substring];
}];
return result;
}
@end
Try it with this test string:
用这个测试字符串试试:
NSString *string = @"ab 132487 387 e e e ";
NSLog(@"%@", [string stringByFormattingAsCreditCardNumber]);
The method works with non-BMP characters (i.e. emoji) and handles existing white space.
该方法适用于非 BMP 字符(即表情符号)并处理现有的空白。
回答by Tony
You should do like this:
你应该这样做:
- (NSString *)resetCardNumberAsVisa:(NSString*)originalString {
NSMutableString *resultString = [NSMutableString string];
for(int i = 0; i<[originalString length]/4; i++)
{
NSUInteger fromIndex = i * 4;
NSUInteger len = [originalString length] - fromIndex;
if (len > 4) {
len = 4;
}
[resultString appendFormat:@"%@ ",[originalString substringWithRange:NSMakeRange(fromIndex, len)]];
}
return resultString;
}
UPDATE:
更新:
You code will be right on the first inserting space charactor:
您的代码将在第一个插入空格字符上:
This is your originalString
:
这是你的originalString
:
Text: 123412341234
Location: 012345678901
Base on your code, on the first you insert space character, you will insert at "1"(with location is 4)
根据您的代码,在您第一次插入空格字符时,您将插入“1”(位置为 4)
And after that, your string is:
在那之后,你的字符串是:
Text: 1234 12341234
Location: 0123456789012
So, you see it, now you have to insert second space charater at location is 9(9%4 !=0)
所以,你看它,现在你必须在位置9(9%4 !=0)插入第二个空格字符
Hope you can fix your code by yourself!
希望你能自己修复你的代码!
回答by Droppy
Your code is pretty close, however a better semantic for the method is to return a new NSString
for any given input string:
您的代码非常接近,但是该方法更好的语义是NSString
为任何给定的输入字符串返回一个新的:
-(NSString *)formatStringAsVisa:(NSString*)aNumber
{
NSMutableString *newStr = [NSMutableString new];
for (NSUInteger i = 0; i < [aNumber length]; i++)
{
if (i > 0 && i % 4 == 0)
[newStr appendString:@" "];
unichar c = [aNumber characterAtIndex:i];
[newStr appendString:[[NSString alloc] initWithCharacters:&c length:1]];
}
return newStr;
}
回答by Szu
The code snippet from heredo what do you want:
从代码段在这里做你想做的事:
- (NSString *)insertSpacesEveryFourDigitsIntoString:(NSString *)string
andPreserveCursorPosition:(NSUInteger *)cursorPosition
{
NSMutableString *stringWithAddedSpaces = [NSMutableString new];
NSUInteger cursorPositionInSpacelessString = *cursorPosition;
for (NSUInteger i=0; i<[string length]; i++) {
if ((i>0) && ((i % 4) == 0)) {
[stringWithAddedSpaces appendString:@" "];
if (i < cursorPositionInSpacelessString) {
(*cursorPosition)++;
}
}
unichar characterToAdd = [string characterAtIndex:i];
NSString *stringToAdd =
[NSString stringWithCharacters:&characterToAdd length:1];
[stringWithAddedSpaces appendString:stringToAdd];
}
return stringWithAddedSpaces;
}
回答by zander zhang
swift3 based on Droppy
基于 Droppy 的 swift3
func codeFormat(_ code: String) -> String {
let newStr = NSMutableString()
for i in 0..<code.characters.count {
if (i > 0 && i % 4 == 0){
newStr.append(" ")
}
var c = (code as NSString).character(at: i)
newStr.append(NSString(characters: &c, length: 1) as String)
}
return newStr as String
}
回答by Wanpaya
Please make sure that your string length should times by 4.
This solution will insert on the right hand side first.
请确保您的字符串长度应乘以 4。
此解决方案将首先插入右侧。
- (NSString*) fillWhiteGapWithString:(NSString*)source
{
NSInteger dl = 4;
NSMutableString* result = [NSMutableString stringWithString:source];
for(NSInteger cnt = result.length - dl ; cnt > 0 ; cnt -= dl)
{
[result insertString:@" " atIndex:cnt];
}
return result;
}