我正在尝试从名字+姓氏中获取名字和姓氏。
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 unichar*,因为 characterAtIndex 返回一个 unichar 而 stringWithCharacters 接受一个 const unichar。
当遇到此行时,这会导致从较小的整数类型警告转换为应用程序崩溃(访问错误)。
为什么 Objective C 中的字符串操作如此复杂?
最佳答案
您可以使用 componentsSeparatedByString: 轻松获取名字和姓氏方法。
NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"];
NSArray *components = [fullName componentsSeparatedByString:@"+"];
NSString *firstName = components[0];
NSString *lastName = components[1];
注意:您需要进行适当的数组边界检查。您也可以使用 NSScanner出于同样的目的。
关于ios - 将 charAtIndex 分配给 stringWithCharacters 会给出无效的转换警告和错误的访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33140379/