将字符串中的每个单词替换为(第一个字母 + 之间的字符数 + 最后一个字母)
Replace each word in a string with (the first letter + number of characters between + last letter)
我正在使用 objective-c 来解析这里的一个句子:
NSString *myString = @“Some words to form a string”;
这是我目前的情况:
NSMutableString *firstCharacters = [NSMutableString string];
NSMutableString *lastCharacters = [myString substringFromIndex:[myString length] - 1]
NSArray *arrayOfWords = [myString componentsSeparatedByString:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in arrayOfWords) {
if ([word length] > 0) {
NSString *firstLetter = [word substringToIndex:1];
[firstCharacters appendString:lastCharacters];
然后我在这一点上真的很困惑。我想 NSLog 重新组合的字符串,这样它看起来像这样:
"S2e w3s to f2m a s3g"
请尝试以下代码:
NSString *myString = @"Some words to form a string";
NSArray *wordsInSentence = [myString componentsSeparatedByString:@" "];
NSMutableArray *expectedResultArray = [[NSMutableArray alloc] init];
for (NSString *word in wordsInSentence) {
NSString *finalExpectedString = word;
if (word.length > 2) {
NSString *firstLetterInWord = [word substringToIndex:1];
NSString *lastLetterInWord = [word substringFromIndex:[word length] - 1];
finalExpectedString = [NSString stringWithFormat:@"%@%d%@", firstLetterInWord, (int)word.length - 2, lastLetterInWord];
}
[expectedResultArray addObject:finalExpectedString];
}
NSString *printString = [expectedResultArray componentsJoinedByString:@" "];
NSLog(@"Result : %@", printString);
我正在使用 objective-c 来解析这里的一个句子:
NSString *myString = @“Some words to form a string”;
这是我目前的情况:
NSMutableString *firstCharacters = [NSMutableString string];
NSMutableString *lastCharacters = [myString substringFromIndex:[myString length] - 1]
NSArray *arrayOfWords = [myString componentsSeparatedByString:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in arrayOfWords) {
if ([word length] > 0) {
NSString *firstLetter = [word substringToIndex:1];
[firstCharacters appendString:lastCharacters];
然后我在这一点上真的很困惑。我想 NSLog 重新组合的字符串,这样它看起来像这样: "S2e w3s to f2m a s3g"
请尝试以下代码:
NSString *myString = @"Some words to form a string";
NSArray *wordsInSentence = [myString componentsSeparatedByString:@" "];
NSMutableArray *expectedResultArray = [[NSMutableArray alloc] init];
for (NSString *word in wordsInSentence) {
NSString *finalExpectedString = word;
if (word.length > 2) {
NSString *firstLetterInWord = [word substringToIndex:1];
NSString *lastLetterInWord = [word substringFromIndex:[word length] - 1];
finalExpectedString = [NSString stringWithFormat:@"%@%d%@", firstLetterInWord, (int)word.length - 2, lastLetterInWord];
}
[expectedResultArray addObject:finalExpectedString];
}
NSString *printString = [expectedResultArray componentsJoinedByString:@" "];
NSLog(@"Result : %@", printString);