我想在目标c中的字符串之间添加一个空格

时间:2014-06-27 05:57:58

标签: objective-c ios7 nsstring

- (IBAction)addSpace:(id)sender {
//here noSpce is a textbox in which i will enter some value
    NSString *one=self.noSpace.text;

    if (one.length==4)
    //if the length of the string is equal to four then it should put a whitespace 
    //in between the string.
    {
        NSString *blank=@"  ";
        NSString *two=[blank. stringByAppendingString:one,index(2)];
        NSString *new=two;


 //here withSpace is another textbox in which i want to show the expected result
            self.withSpace.text=new;
        }

//this really does not work for me

2 个答案:

答案 0 :(得分:0)

  

NSString * two = [空白。 stringByAppendingString:一,索引(2)];

方法调用中.之后有一个无关的blank。删除它和index(2),您的代码应该更好。

使用可变字符串可以改善您的代码。您可以使用-insertString:atIndex:并避免使用所有这些中间字符串。

更新:您还应该更改new变量的名称。 new是NSObject中方法的名称,也是C ++中的保留字。使用它作为变量名称应该有效,但它将来会导致混淆。

答案 1 :(得分:0)

- (IBAction)addSpace:(id)sender
{
//here noSpace is a textBox 
    NSMutableString *string1=[NSMutableString stringWithString:self.noSpace.text];
    //this was what i was looking for. . . 
    [string1 insertString:@" " atIndex:2];
    //showing result of noSpace textBox in withSpace textBox.
    self.withSpace.text=string1;

}