Ladessa
Ladessa

Reputation: 1003

Need to substring the last white spaces

I have the string

"Avenida Indianopolis                , 1000"

and I need get "Avenida Indianopolis, 1000"

How can I do this?

Upvotes: 1

Views: 192

Answers (4)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

I think the key to this is you need to remove all the spaces before the ','.

For that, use the regular expression @" +,": one or more spaces followed by a comma.

NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@" +," options:0 error:NULL];

NSMutableString *data = [NSMutableString stringWithString:@"Avenida Indianopolis      , 1000"];
[re replaceMatchesInString:data options:0 range:NSMakeRange(0, data.length) withTemplate:@","];

STAssertEqualObjects(data, @"Avenida Indianopolis, 1000", nil);

Upvotes: 0

JustSid
JustSid

Reputation: 25318

You can use a regular expression to replace everything with two or more spaces with one space:

 {2,}

Example:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" {2,}" options:0  error:NULL];

NSMutableString *string = [NSMutableString stringWithString:@"Avenida Indianopolis      , 1000"];
[regex replaceMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@" "];

However, in your example this would result in a space before the comma, so you might actually want to replace the spaces with nothing (or run a second pass over the string and clean up the space + comma, depending on how your input strings are formed)

Upvotes: 2

Girish
Girish

Reputation: 4712

Try

NSString *str = "Avenida Indianopolis &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp, 1000";
str = [str stringByReplacingOccurrencesOfString:@"&nbsp" withString:@""]; 

Try this if space is present instead of &nbsp

NSString *str = "Avenida Indianopolis    , 1000";
str = [str stringByReplacingOccurrencesOfString:@"     " withString:@""]; 

Upvotes: 1

P.J
P.J

Reputation: 6587

Try this

NSString *string = @"Avenida Indianopolis &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp, 1000";
string = [string stringByReplacingOccurrencesOfString:@"&nbsp" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@"&nbsp " withString:@""];

Hope it helps you..

EDIT

NSString *string = @"Avenida Indianopolis &nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp, 1000";
string = [string stringByReplacingOccurrencesOfString:@"     " withString:@" "];

Upvotes: 0

Related Questions