Is CapitalizedString misusing words starting with numbers?

I use the NSString [myString capitalizedString] method to use all the words in my string.

However, for words starting with numbers, capitalization does not work very well.

ie 2nd chance 

becomes

 2Nd Chance 

Even if n is not the first letter of the word.

thanks

+4
source share
2 answers

You need to give up your own solution to this problem. Apple docs states that you cannot get the specified behavior with this function for verbose strings and for strings with special characters. Here's a pretty rude decision

 NSString *text = @"2nd place is nothing"; // break the string into words by separating on spaces. NSArray *words = [text componentsSeparatedByString:@" "]; // create a new array to hold the capitalized versions. NSMutableArray *newWords = [[NSMutableArray alloc]init]; // we want to ignore words starting with numbers. // This class helps us to determine if a string is a number. NSNumberFormatter *num = [[NSNumberFormatter alloc]init]; for (NSString *item in words) { NSString *word = item; // if the first letter of the word is not a number (numberFromString returns nil) if ([num numberFromString:[item substringWithRange:NSMakeRange(0, 1)]] == nil) { word = [item capitalizedString]; // capitalize that word. } // if it is a number, don't change the word (this is implied). [newWords addObject:word]; // add the word to the new list. } NSLog(@"%@", [newWords description]); 
+5
source

Unfortunately, this is similar to the general behavior of capizedizedString.

Perhaps a not-so-nice workaround / hack will replace each number with a string before the conversion, and then change it again.

So, "second chance" β†’ "xyznd chance" β†’ "Xyznd Chance" β†’ "2nd Chance"

0
source

Source: https://habr.com/ru/post/1400241/