0

I would like to add a spacing between two words if its already not there:

//Sample 1
NSString *word1 = @"First";
NSString *word2 = @"Word";

NSString *output = [NSString stringWithFormat:@"%@%@", word1, word2];
//output = FirstWord --> I want "First Word"

If there is already a space "First " then it should not add another one.

codeNinja
  • 1,442
  • 3
  • 25
  • 61
  • 2
    Why do you think you need a regex for this? Why not check if `word1` ends in whitespace or `word2` begins with whitespace and if not, put a space in between them? – Itai Ferber Mar 01 '17 at 01:15
  • Just [trim the first string](http://stackoverflow.com/q/5756256/3141234), and then always put a space. – Alexander Mar 01 '17 at 01:17

1 Answers1

0

Just trim the first string, and then always put a space.

NSString *word1 = @"First";
NSString *word2 = @"Word";

NSString *word1Trimmed = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceCharacterSet]];
NSString *output = [NSString stringWithFormat:@"%@ %@", word1Trimmed, word2];
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • What if `word2` begins with a space? What if `word1` ends in 1,000,000 spaces? Why do the extra work? – Itai Ferber Mar 01 '17 at 01:18
  • @ItaiFerber I'm answering the direct question `If there is already a space "First " then it should not add another one.` – Alexander Mar 01 '17 at 01:19