18979

How do I remove all unnecessary whitespace from a string?

Question:

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

The \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:@" "];

Recommend

  • How to create an HTML link in Dart?
  • ASP.NET MVC Drop Down List
  • Regular Expression to identify a Guid followed by a number
  • What is the difference between CacheStoreMode USE and REFRESH
  • sscanf: get first and last token in a string
  • Code to disable magnifier, set wallpaper, and save image in Google Chrome?
  • HSQL + Hibernate Exception: Wrong column type: Found: double, expected: float
  • d3js: time scaling and “1901”
  • PHP & cURL proxy - how to make multi-user cookie jar?
  • How can I see all the files that were modified/added/removed in the last push received?
  • Gradle - How to detect --debug flag from command line?
  • substitute period from abbreviation (single letter + period) unless followed by a capital letter
  • Get XML response value with GDataXML
  • how to sort an arraylist that contains string arrays?
  • HTTP Module intercept requests and breaks custom errors configuration
  • How to bind comma separated list of values to List
  • Tinymce strips attributes on submit
  • Visual studio alerts workspace already exists
  • Create a multiple screen android application
  • help('modules') crashing? Not sure how to fix
  • SQL Server re-calculate or not?
  • Can XOR be expressed using SKI combinators?
  • Raphael.js function getBBox give back NAN/NAN/NAN in IE8
  • matching similar elements in between two lists
  • Use sed with regex and (
  • IE10 strips out hashtag from the URL
  • Create a link to a web page that runs a Javascript function on the page
  • jQuery: add elements until a particular height is reached
  • uml Composition relationships to RDF and OWL
  • Azure table store snapshot/backup capability
  • xtable package: Skipping some rows in the output
  • x64 applications using gdi+: what are the consequences on performance?
  • Change JButton Shape while respecting Look And Feel
  • Deserializing XML into class C#
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • PHP: When would you need the self:: keyword?
  • python regex in pyparsing
  • python draw pie shapes with colour filled
  • Does armcc optimizes non-volatile variables with -O0?
  • How to Embed XSL into XML