Teddy13
Teddy13

Reputation: 3854

add whitespace to string

I have the following string

NSString *word1=@"hitoitatme";

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

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.

Thank you in advance

Upvotes: 1

Views: 2793

Answers (2)

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

You can do this way:

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

Upvotes: 5

nsgulliver
nsgulliver

Reputation: 12671

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

Upvotes: 7

Related Questions