将charAtIndex分配给stringWithCharacters会导致无效的投射警告和访问错误
问题描述:
我试图从firstname + lastname中获取名字和姓氏。将charAtIndex分配给stringWithCharacters会导致无效的投射警告和访问错误
int loop=0;
NSMutableString *firstname = [[NSMutableString alloc]init];
NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"];
for (loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) {
[firstname appendString:[NSString stringWithCharacters:(const unichar *)[fullName characterAtIndex:loop] length:1]];
}
NSLog(@"%@",firstname);
我试图从类型转换为unichar为const单字符*因为characterAtIndex返回一个单字符,但stringWithCharacters接受一个const单字符。
这会导致从较小的整数类型警告转换,并遇到此行时应用程序崩溃(访问不良)。
为什么Objective C中的字符串操作如此复杂?
答
尝试了这一点:
NSMutableString *firstname = [[NSMutableString alloc] init];
NSMutableString *fullName = [[NSMutableString alloc] initWithString:@"Anahita+Havewala"];
for (NSUInteger loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) {
unichar myChar = [fullName characterAtIndex:loop];
[firstname appendString:[NSString stringWithFormat:@"%C", myChar]];
}
NSLog(@"%@", firstname);
答
您可以很容易地得到名字和最后使用componentsSeparatedByString:方法。
NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"];
NSArray *components = [fullName componentsSeparatedByString:@"+"];
NSString *firstName = components[0];
NSString *lastName = components[1];
注:你需要做适当的数组边界检查。您也可以使用NSScanner来达到同样的目的。
+0
我会怎么做一个数组边界检查?我不知道'+'之前或之后会有多少个角色。如果我需要找出来,我不得不使用characterAtIndex。 – SeeObjective
您的解决方案一如既往地出色。谢谢! – SeeObjective
总是乐于帮助!很高兴它帮助你:)! – Abhinav
不知道为什么我在这里得到了投票。请发布投票的理由! – Abhinav