IOS removes spaces or extra spaces in a string (for English words)

Source: Internet
Author: User
Nsstring-stringbytrimmingcharactersinset: It's a method you need to keep in mind. It often passes in Nscharacterset +whitespacecharacterset or +whitespaceandnewlinecharacterset to remove the blank symbol at the ends of the input string.


It is important to note that this method removes only the contiguous characters in the specified character set at the beginning and end. This means that if you want to remove the extra space between words, see the next step.


Let's say you remove the extra space at both ends of the string, and you want to remove the extra space between the words, here's a very simple way:

NSString *string = @ "Lorem ipsum dolar sit amet.";

string = [string Stringbytrimmingcharactersinset:[nscharacterset whitespacecharacterset]];

Nsarray *components = [string Componentsseparatedbycharactersinset:[nscharacterset whitespacecharacterset]];

components = [Components filteredarrayusingpredicate:[nspredicate predicatewithformat:@ "self <>"]];

string = [Components componentsjoinedbystring:@ ""];//split by single space

The steps are: first, remove the trailing spaces of the string, and then use Nsstring-componentsseparatedbycharactersinset: to divide the string into a nsarray in the space; and then remove the empty string with a nspredicate; , using nsarray-componentsjoinedbystring: To use a single spaces to spell the array back into a string. Note: This method is only applicable to English language which is separated by space.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.