I pull some text from a website and save it in an NSString, and display it back to the user, but I want it in one clear line, one word after another word, with absolutely zero line-breaks or unnecessary whitespace or tabs.
Take the following image:
<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/iSU7O.png" data-original="https://i.stack.imgur.com/iSU7O.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />
Body has all this spacing in it that I don't want. I do want spaces between words (so I want "This is a sentence", NOT "Thisisasentence") but all that spacing is really making the output ugly. How do I get rid of it?Answer1:
Regular expressions help a lot here:
NSString *tooManySpaces = @" Too\tmany spaces \n and on several \nlines, at that"; NSString *cleaned = [tooManySpaces stringByReplacingOccurrencesOfString: @"\\s+" withString: @" " options: NSRegularExpressionSearch range: NSMakeRange(0, tooManySpaces.length)];
\s pattern covers whitespace, i.e. space, tab and newline. If that is too much, you can specify those that you need , like this:
[ \t]+ to cover space and tab characters.
In order to remove any excess whitespace at the beginning and the end, you also need to trim the string (either before or after applying the regex substitution):
cleaned = [cleaned stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];Answer2:
Use a regular expression to replace the pattern
@" +" (space space plus) with
@" " (space).
In other words, this will replace all occurrences of two or more spaces with a single space.
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" +" options:0 error:&error]; NSString *someString = ...; // some string with lots of spaces NSString *newString = [regex stringByReplacingMatchesInString:someString options:0 range:NSMakeRange(0, someString.length) withTemplate:@" "];