capitalizedString没有正确地大写以数字开头的单词?

ane*_*yzm 4 cocoa objective-c

我正在使用NSString方法[myString capitalizedString]来大写我的字符串中的所有单词.

但是,对于以数字开头的单词,大小写不能很好地工作.

i.e. 2nd chance
Run Code Online (Sandbox Code Playgroud)

2Nd Chance
Run Code Online (Sandbox Code Playgroud)

即使n不是单词的第一个字母.

谢谢

Pet*_*lly 5

你必须为这个问题推出自己的解决方案.在苹果公司的文档说明您可能没有使用该功能进行多字的字符串以及具有特殊字符的字符串获得指定的行为.这是一个非常粗糙的解决方案

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]);
Run Code Online (Sandbox Code Playgroud)

  • 好的解决方案 我切换了`[newWords description];`for` [[newWords valueForKey:@"description"] componentsJoinedByString:@""];`但是,前者将返回一个包含括号和换行符的字符串. (2认同)