Nscharacterset
As before, the base Class Library (foundation) has the best, most functional, and most complete implementation of the String class.
But the implementation of a string is really good only when the programmer is mastering it. So this week, we're going to look at some of the most important parts of the string ecosystem of the base class library that are often used and used incorrectly: NSCharacterSet .
If you're not sure what a character encoding is (even if you have a good professional knowledge), then you should take this opportunity to read the classic article "the Absolute Minimum every software Developer" from Joel Spolsky. Absolutely, positively must Know about Unicode and Character sets (No excuses!) ". Staying fresh in your mind will be very helpful in understanding the topic that we are going to explore.
NSCharacterSet, and its mutable version NSMutableCharacterSet , which represents a set of Unicode characters in an object-oriented manner. It is often NSString combined with and NSScanner used to filter, delete, or split on different characters. To give you a visual impression of which characters these characters are, take a look at NSCharacterSet the class method provided:
-
alphanumericCharacterSet
-
capitalizedLetterCharacterSet
-
controlCharacterSet
-
decimalDigitCharacterSet
-
decomposableCharacterSet
-
illegalCharacterSet
-
letterCharacterSet
-
lowercaseLetterCharacterSet
-
newlineCharacterSet
-
nonBaseCharacterSet
-
punctuationCharacterSet
-
symbolCharacterSet
-
uppercaseLetterCharacterSet
-
whitespaceAndNewlineCharacterSet
-
whitespaceCharacterSet
Contrary to its name, NSCharacterSet NSSet there is no relationship.
Although the underlying implementations are not quite the same, NSCharacterSet they are NSIndexSet somewhat similar in concept. NSIndexSet, as previously mentioned, represents a collection of ordered, non-repeating unsigned integers. Unicode characters are similar to unsigned integers and roughly correspond to some spelling representations. Therefore, a NSCharacterSet +lowercaseCharacterSet character set is equivalent to a range that contains 97 to 122 NSIndexSet .
Now that we have a NSCharacterSet little confidence in the basic concept of understanding, let's look at some of its patterns and anti-patterns:
Remove spaces
NSString -stringByTrimmingCharactersInSet:is a method you need to keep in mind. It often passes in NSCharacterSet +whitespaceCharacterSet or +whitespaceAndNewlineCharacterSet out to remove the white space symbol of the input string's kinsoku.
It is important to note that this method only removes successive characters from the specified character set at the beginning and end . This means that if you want to remove the extra space between words, see next.
Squeeze spaces
If you remove the extra spaces at both ends of the string and want to remove the extra space between the words, here's a very handy way to do this:
Objective-c
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:@ "];
First, remove the whitespace from the beginning and end of the string, then NSString -componentsSeparatedByCharactersInSet: divide the string into one using a space, then NSArray use one to remove the empty string NSPredicate , and finally, use a NSArray -componentsJoinedByString: single whitespace to re-spell the array into a string. Note: This method only applies to English as a space-delimited language.
Now look at the anti-pattern. Please first look at the answers to this question on StackOverflow.
At the time of writing this article, the right answer to the second ranking is 58 tops and 2 steps. Ranked first with 84 tops and 24 treads.
Now, the first answer is not the correct answer is not very normal, but this problem has broken the number of answers (10) of the record, but also broke the number of non-repetition, the total wrong Answer (9) records.
To get to the point, here are 9 wrong answers:
-
"Use stringByTrimmingCharactersInSet "- as you know, it only removes the trailing spaces.
-
"Replace" with "- this removes all the blanks, vain.
-
"Use a regular expression"- it's a bit of a deal, but it doesn't handle the trailing spaces. Using regular expressions is a bit overqualified.
-
"Use Regexp Lite"- honestly, regular expressions are really not necessary. Adding third-party libraries for this feature is not worth it.
-
"Use Ogrekit"- ibid., added third-party libraries.
-
"Split the string into the components, iterate through them to find, and non-zero length, and then Re-combine"- very Close, but componentsSeparatedByCharactersInSet: has made traversal unnecessary.
-
"Replace two-space strings with single-space strings in a while loop"- error and wasteful compute resources.
-
"Manually iterate over unichar NSCharacterSet -characterIsMember: every in the string and use"- a complex and surprising way of doing it, forgetting that there are methods available in the standard library.
-
"Find and remove all of the tabs"- has anyone mentioned a tab? Thank you, though.
I personally do not want to blame people who answer questions-just to point out how many different ways to do this, and how many of these methods are completely wrong.
String participle
don't use NSCharacterSet participle. used CFStringTokenizer to replace it.
You can be forgiven for using componentsSeparatedByCharactersInSet: it to clean up user input, but with it to do something more complicated, you will fall into the abyss of pain.
Why? Remember that languages do not all use spaces as a dividing word. Although the language used in the space demarcation is actually very extensive. But even in China and Japan, there are already more than 1 billion people, accounting for 16% of the world's population.
...... Even in a space-delimited language, participle has some ambiguous boundary conditions, especially compound words and punctuation marks.
This is just a description: If you want to divide the string into meaningful words, then use CFStringTokenizer (or enumerateSubstringsInRange:options:usingBlock: ).
Parsing data from a string
NSScanneris a class used to parse data for arbitrary or semi-structured strings. When you create a scanner for a string, you can specify which characters to omit, which prevents those characters from being included in the parsed results in a variety of ways.
For example, you want to parse out the opening time from such a string:
Text
mon-thurs:8:00-18:00 fri:7:00-17:00 sat-sun:10:00-15:00
You will enumerateLinesUsingBlock: use one to parse it like this NSScanner :
Swiftobjective-c
Let skippedcharacters = nsmutablecharacterset () Skippedcharacters.formintersectionwithcharacterset (Nscharacterset.punctuationcharacterset ()) Skippedcharacters.formintersectionwithcharacterset (Nscharacterset.whitespacecharacterset ()) string.enumeratelines { (line, _) in let scanner = nsscanner (String: line) scanner.charactersToBeSkipped = skippedcharacters var startday, endday: nsstring? var starthour: int = 0 var startminute : int = 0 var endhour: int = 0 var endMinute: Int = 0 Scanner.scancharactersfromset (Nscharacterset.lettercharacterset (), intostring: &startday) & NBsp; scanner.scancharactersfromset (Nscharacterset.lettercharacterset (), intoString: &endday) scanner.scaninteger (&starthour) scanner.scaninteger (&startminute) scanner.scaninteger (&endHour) scanner.scaninteger (&endminute) }
We first construct one from the set of whitespace character sets and the punctuation character set NSMutableCharacterSet . Tells you NSScanner to ignore these characters to greatly reduce the necessary logic to parse these characters.
scanCharactersFromSet:The incoming alphabetic character set gets the number of days to start and end (optional) within one week of each item. scanIntegerSimilarly, the next consecutive integer value is obtained.
NSCharacterSetAnd NSScanner allows you to code quickly and confidently. The two are perfect combinations.
NSCharacterSetis a member of the string processing system in the base Class library, which is probably the one that is most likely to be wrong or misunderstood. By remembering these patterns and anti-patterns in your mind, you will not only be able to do something useful such as managing spaces and reading information from strings, but more importantly, you will avoid going astray.
If "no error" is not the most important thing for a nshipster, then I do not want to be the right one!
Nscharacterset String Eco-Library