【问题标题】:Replace each word in a string with (the first letter + number of characters between + last letter)将字符串中的每个单词替换为(第一个字母 + 之间的字符数 + 最后一个字母)
【发布时间】:2015-12-29 05:43:15
【问题描述】:

我这里用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"

【问题讨论】:

  • "S2e w3s to f2m a s4g"?
  • 一旦你填充了一个NSArray,你可以使用componentsSeparatedByString:的反向方法:componentsJoinedByString:

标签: objective-c string parsing append


【解决方案1】:

请尝试以下代码:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2021-01-11
    • 2017-02-13
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多