将空格添加到字符串

Ted*_*y13 1 xcode objective-c ios

我有以下字符串

NSString *word1=@"hitoitatme";
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,如果您要在每隔一个字符后添加一个空格,那么它将是包含最小/最多2个字符的单词串.

NSString *word2=@"hi to it at me";
Run Code Online (Sandbox Code Playgroud)

我想能够在每2个字符后为我的字符串添加一个白色字符空间.我该怎么做呢?所以,如果我有一个像word1这样的字符串,我可以添加一些代码使它看起来像word2?我正在寻找最有效的方法来做到这一点.

先感谢您

nsg*_*ver 7

可能有不同的方法在字符串中添加空格,但一种方法可能是使用NSRegularExpression

  NSString *originalString = @"hitoitatme";
  NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"([a-z])([a-z])" options:0 error:NULL];
  NSString *newString = [regexp stringByReplacingMatchesInString:originalString options:0 range:NSMakeRange(0, originalString.length) withTemplate:@"$0 "];
  NSLog(@"Changed %@", newString);//hi to it at me
Run Code Online (Sandbox Code Playgroud)


Ano*_*dya 5

你可以这样做:

NSString *word1=@"hitoitatme";
NSMutableString *toBespaced=[NSMutableString new];

for (NSInteger i=0; i<word1.length; i+=2) {
    NSString *two=[word1 substringWithRange:NSMakeRange(i, 2)];
    [toBespaced appendFormat:@"%@  ",two ];
}

NSLog(@"%@",toBespaced);
Run Code Online (Sandbox Code Playgroud)