[a characterAtIndex:0] = [b characterAtIndex:0];
我想将 charAt a 分配给 charAt b。
但是失败了,怎么办?
[a characterAtIndex:0] = [b characterAtIndex:0];
我想将 charAt a 分配给 charAt b。
但是失败了,怎么办?
NSMutableString *a = [NSMutableString stringWithString:@"HOUSE" ];
NSString *b= @"MUSIC";
[a replaceCharactersInRange:NSMakeRange(0, 1) withString:[b substringWithRange:NSMakeRange(0, 1)]];
结果你得到了鼠标;-)
如果您正在寻找这样的方法:setCharacter:atIndex:
然后看下面的代码:
NSMutableString *string=[NSMutableString stringWithString:@"abcdefgh"];
[string setCharacter:'X' atIndex:0]; //Note X is character not string so "X" and its is primitive therefore even @ is not prefixed.
NSLog(@"%@",string);
这是通过NSMutableString
其方法实现的类别来实现的
@implementation NSMutableString (SetCharacterAtIndex)
- (void)setCharacter:(char)character atIndex:(NSUInteger)index;{
[self replaceCharactersInRange:NSMakeRange(index, 1) withString:[NSString stringWithFormat:@"%c",character]];
}
编辑:
有了上述方法后,您可以使用:
[a characterAtIndex:0] = [b characterAtIndex:0];
[a setCharacter:[b characterAtIndex:0] atIndex:0];