gpt4 book ai didi

objective-c - capitalizedString 不能正确大写以数字开头的单词?

转载 作者:太空狗 更新时间:2023-10-30 04:02:23 26 4
gpt4 key购买 nike

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

但是,对于以数字开头的单词,大写不是很好。

i.e. 2nd chance

成为

2Nd Chance

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

谢谢

最佳答案

你必须推出自己的解决方案来解决这个问题。 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]);

关于objective-c - capitalizedString 不能正确大写以数字开头的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9605063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com