将空格添加到string

我有以下string

NSString *word1=@"hitoitatme"; 

正如你所看到的,如果你要在每个第二个字符之后加一个空格,那么它将是一个包含最小/最大2个字符的string。

 NSString *word2=@"hi to it at me"; 

我希望能够在每2个字符后为我的string添加一个白色字符空间。 我怎么去做这个? 所以,如果我有一个string,如word1,我可以添加一些代码,使其看起来像word2? 我正在寻找如果可能的最有效的方式做到这一点。

先谢谢你

可能有不同的方式来在string中添加空格,但有一种方法可以使用NSRegularExpression

  NSString *originalString = @"hitoitatme"; NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"([az])([az])" 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 

你可以这样做:

 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);