向字符串添加空格 [英] add whitespace to string

查看:58
本文介绍了向字符串添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串

NSString *word1=@"hitoitatme";

如您所见,如果您要在每第二个字符后添加一个空格,它将是一串包含最少/最多 2 个字符的单词.

as you can see, if you were to add a space after every second character, it would be a string of words that contain min/max 2 characters.

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

我希望能够在每 2 个字符后为我的字符串添加一个空格.我该怎么做呢?那么如果我有一个像word1这样的字符串,我可以添加一些代码让它看起来像word2吗?如果可能,我正在寻找最有效的方法.

I want to be able to add a white character space to my string after every 2 characters. How would I go about doing this? So if I have a string such as word1, I can add some code to make it look like word2? I am looking if possible for the most efficient way of doing this.

提前致谢

推荐答案

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

There might be different ways to add white space in the string but one way could be using 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

这篇关于向字符串添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆