Brijesh Singh
Brijesh Singh

Reputation: 739

How can i trim spaces from between of a NSString while displaying in UI Label

I am getting the string value from web service.I need to remove spaces from between of a string. How can I do that? Example:if string is "A ALL YEAR" it must become "A ALL YEAR" while displaying the value in UILabel text.

I have attached the below image for clarification.

enter image description here

Upvotes: 0

Views: 62

Answers (3)

Kundan
Kundan

Reputation: 3082

NSString *yourString = @"A  ALL YEAR";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:@" "];

Output:- A ALL YEAR

Hope you need this. If this doesn't work, let me know.

Upvotes: 2

NeverHopeless
NeverHopeless

Reputation: 11233

Try NSRegularExpression class with this regex pattern:

\s{2,}

and replace is with space.

Regex Demo

Example of NSRegualrExpression for string replacement.

Upvotes: 0

Suhaib
Suhaib

Reputation: 2061

let str = "A All Time".components(separatedBy: " ")

let newString = str[0] + " " + str[1] + " " + str[3]

You can also use a for loop.

Upvotes: 0

Related Questions