2012-03-07 61 views
4

我正在使用NSString方法[myString capitalizedString],來大寫我的字符串的所有單詞。capitalizedString不正確地大寫正確的單詞開頭的數字?

但是大寫字母對於以數字開頭的單詞不起作用。

i.e. 2nd chance 

成爲

2Nd Chance 

即使n不是單詞的第一個字母。

謝謝

+0

這可能幫助:http://www.pittle.org/weblog/how-to-capitalize-a-nsstring-instance-while-keeping-roman-numerals-all-capitalized_536 .html – 2012-03-07 16:22:29

回答

5

你必須推出自己的解決這個問題。 Apple docs指出,對於多字字符串和具有特殊字符的字符串,您可能無法獲得指定的行爲。這裏是一個非常粗液

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

不錯的解決方案。我爲''[newWords valueForKey:@「description」]切換了'[newWords description];''componentsJoinedByString:@「」];'但是,前者將返回一個包含圓括號和換行符的字符串。 – 2013-11-06 22:05:53

+0

解決了我的問題 – Hassy 2017-06-05 05:24:10

0

不幸的是,這似乎是capitalizedString的一般行爲。

也許一個不是很好的解決方法/破解將在轉換之前用一個字符串替換每個數字,然後再將其更改回來。

因此, 「第二次機會」 - > 「xyznd機會」 - > 「Xyznd機會」 - > 「第二次機會」

+0

事實上,它不是很好的破解,有沒有其他解決方案? – aneuryzm 2012-03-07 16:41:46