0

I'm trying to manipulate an NSString. I want to neaten up the output. If there are multiple spaces in a row, they should be replaced with a newline.

NSString *myString = @"Name: Tom Smith           Old address       street name : 31 Fox Road      Dixton       0000";

My desired output from NSLog():

Name: Tom Smith                  
Old address     
street name : 31 Fox Road                  
Dixton         
0000

Here's a bit of logic I have been working on. I'm not sure if it's correct.

    if (word_spacing > 1)
        insert word in new line "\n"
    else
        carry on from the same line
jscs
  • 63,694
  • 13
  • 151
  • 195
  • You checked this? http://stackoverflow.com/questions/6608420/how-to-remove-whitespace-in-a-string – MrBr Feb 11 '14 at 06:15
  • @ MrBr i have and it doesn't give me that very same desired output – Nhlanhla Khumalo Feb 11 '14 at 06:17
  • 1
    this needs more info.. are u trying to display this string on a label? whats the output ur getting? and is this string hardcoded or ur getting it like this from some webservice ?? – Sharanya K M Feb 11 '14 at 06:27
  • possible duplicate of [Collapse sequences of white space into a single character](http://stackoverflow.com/q/758212) and see also [Removing multiple spaces in NSString](http://stackoverflow.com/q/12136970) – jscs Feb 11 '14 at 06:34

5 Answers5

2

You can do it by using NSCharacterSet and componentsSeparatedByString.

Solution :

// Your string
NSString *myString = @"Name: Tom Smith           Old address       street name : 31 Fox Road      Dixton       0000";

// Seperating words which have more than 1 space with another word
NSArray *components    = [myString componentsSeparatedByString:@"  "];
NSString *newString    = @"";
NSString *oldString    = @"";
for (NSString *tempString in components)
{
    // Creating new string
    newString = [oldString stringByAppendingString:[tempString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];

    // Avoiding new line characters or extra spaces contained in the array
    if (![oldString isEqualToString:newString])
    {
        newString = [newString stringByAppendingString:@"\n"];
        oldString = newString;
    }
}
NSLog(@"%@",newString);

or

You can use NSRegularExpression

NSString *pattern = [NSString stringWithFormat:@"  {2,%d}",[myString length]];

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

NSString *output = [regex stringByReplacingMatchesInString:myString options:0 range:NSMakeRange(0, [myString length]) withTemplate:@"\n"];
NSLog(@"%@", output);
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0

You could give it a try using:

NSArray *results = [myString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":"]],

wich returns an array containing substrings from the receiver that have been divided by characters in a given set.

Once you have that just loop through the result incrementing by 2 and you'll get the key value pairs. Then you could do some sort of trimming in the value for each key value pair using:

NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceCharacterSet]]; 
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

You could split the string by the character you want (in your case more than one space) like this:

NSArray * components = [myString componentsSeparatedByString: @"  "];

Then you can print out each component followed by a newline:

for (NSString * component in components) {
    NSLog(@"%@\n",component);
}
Gad
  • 2,867
  • 25
  • 35
0

If you have unpredictable between the strings and you want to replace multiple spaces with new line then you should go with regex. The regex you are using will not work since it pick spaces one or more time but actually you want to pick two or more times.

I know this thread is already solved but have a look at this sample as well:

NSString *myString = @"Name: Tom Smith           Old address       street name : 31 Fox Road      Dixton       0000";

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}" options:NSRegularExpressionCaseInsensitive error:&error];

NSArray *arr = [regex matchesInString:myString options:NSMatchingReportCompletion range:NSMakeRange(0, [myString length])];

arr = [[arr reverseObjectEnumerator] allObjects];

for (NSTextCheckingResult *str in arr) {
    myString = [myString stringByReplacingCharactersInRange:[str range] withString:@"\n"]; }

NSLog(@"%@", myString);

Output log:

Name: Tom Smith
Old address
street name : 31 Fox Road
Dixton
0000

Live Demo

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
0

//Call a method like:

    NSString *descriptionStr = [self stringByRemovingBlankLines:string];;

//Method

- (NSString *)stringByRemovingBlankLines : (NSString *)stringValue
{
NSScanner *scan = [NSScanner scannerWithString:stringValue];
NSMutableString *string = NSMutableString.new;
while (!scan.isAtEnd) {
    [scan scanCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:NULL];
    NSString *line = nil;
    [scan scanUpToCharactersFromSet:NSCharacterSet.newlineCharacterSet intoString:&line];
    if (line) [string appendFormat:@"%@\n",line];
}
if (string.length) [string deleteCharactersInRange:(NSRange){string.length-1,1}]; // drop last '\n'
return string;
}
Mannam Brahmam
  • 2,225
  • 2
  • 24
  • 36