将characterAtIndex指定给characterAtIndex

时间:2013-02-28 08:07:02

标签: objective-c

[a characterAtIndex:0] = [b characterAtIndex:0];

我想将charAt a指定给charAt b。

但失败了,怎么样?

2 个答案:

答案 0 :(得分:0)

  NSMutableString *a = [NSMutableString stringWithString:@"HOUSE" ];

  NSString *b= @"MUSIC";

 [a replaceCharactersInRange:NSMakeRange(0, 1) withString:[b substringWithRange:NSMakeRange(0, 1)]];

结果你得到了MOUSE ;-)

答案 1 :(得分:0)

如果您正在寻找类似这样的方法: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];