我遇到以下代码的问题。我希望结果multiLineTitle
看起来像这样
Each
Word
Should
Have
Its
Own
Line
但是当我运行此程序时,multiLineTitle
结束null
。有谁能发现这个问题?
NSString *title = "Each Word Should Have Its Own Line";
NSString *multiLineTitle;
NSArray *words = [title componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];
for (int len = 0; len < [words count]; len++){
multiLineTitle = [multiLineTitle stringByAppendingFormat:@"%@ \n", words[len]];
}
答案 0 :(得分:1)
将空字符串分配给multiLineTitle
或为multiLineTitle分配内存。
NSString *multiLineTitle = @"";
或
NSString *multiLineTitle = [[NSString alloc]init];
答案 1 :(得分:0)
solution....
NSString *title =@"Each Word Should Have Its Own Line";
NSMutableString *multiLineTitle =[[NSMutableString alloc] init];
NSArray *words = [title componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
words = [words filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];
for (int len = 0; len < [words count]; len++){
[multiLineTitle appendFormat:@"%@\n",[words objectAtIndex:len]];
}
NSLog(@"multiLineTitle:%@",multiLineTitle);
ans:
multiLineTitle:Each
Word
Should
Have
Its
Own
Line