Nhlanhla Khumalo
Nhlanhla Khumalo

Reputation: 13

Replace multiple spaces with a newline but leave single spaces

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

Upvotes: 0

Views: 1095

Answers (5)

Mannam Brahmaiah
Mannam Brahmaiah

Reputation: 2283

//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;
}

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

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

Upvotes: 0

Midhun MP
Midhun MP

Reputation: 107131

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

Upvotes: 2

Gad
Gad

Reputation: 2877

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

Upvotes: 0

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

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

Upvotes: 0

Related Questions