gpt4 book ai didi

objective-c - 使用 objective-c 获取字符串中每个单词的第一个字母

转载 作者:太空狗 更新时间:2023-10-30 03:21:16 25 4
gpt4 key购买 nike

我正在尝试做的事情的例子:

String = "这是我的句子"

我希望得到这个结果:“TIMS”

出于某种原因,我正在努力使用 objective-c 和字符串

最佳答案

天真的解决方案:

NSMutableString * firstCharacters = [NSMutableString string];
NSArray * words = [@"this is my sentence" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for (NSString * word in words) {
if ([word length] > 0) {
NSString * firstLetter = [word substringToIndex:1];
[firstCharacters appendString:[firstLetter uppercaseString]];
}
}

请注意,这对于拆分单词有点愚蠢(只是按空格,这并不总是最好的方法),并且它不处理 UTF16+ 字符。

如果您需要处理 UTF16+ 字符,请将循环内的 if() 语句更改为:

if ([word length] > 0) {
NSString * firstLetter = [word substringWithRange:[word rangeOfComposedCharacterSequenceAtIndex:0]];
[firstCharacters appendString:[firstLetter uppercaseString]];
}

关于objective-c - 使用 objective-c 获取字符串中每个单词的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3259240/

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