【问题标题】:Concatenating an int to a string in Objective-c在 Objective-c 中将 int 连接到字符串
【发布时间】:2013-02-18 09:11:17
【问题描述】:

我如何将int length 连接到我试图插入该数组的字符串,所以它是“C10”,当然,给定长度 == 10。我看到@"%d", intVarName 在其他地方使用的方法。在 Java 中,我会完成 "C" + length;。我正在使用replaceObjectAtIndex 方法替换我之前填充MSMutableArray "board" 的空字符串""。但是,当我在该方法的末尾添加 @"C%d", length 部分时出现错误倒数第二行,在 i++ 上方)

作为我作业的一部分,我必须随机放置“Chutes”(由格式字符串“C'length_of_chute'”表示,在第一个作业中,它们的长度始终为 10,因此它只是“C10” ) 到由数组表示的游戏板上。

   -(void)makeChutes: (int) length {// ??Change input to Negative number, Nvm.
    //??Make argument number of Chutes ??randomly?? across the board.
    for(int i = 0; i < length;){
        int random = arc4random_uniform(101);
        if ([[board objectAtIndex:random] isEqual:@""]) {
            //[board insertObject:@"C%d",length atIndex:random];
            [board replaceObjectAtIndex:random withObject:@"C%d",length];
            i++;
        }
    }
}

请忽略其中的多余和垃圾代码,我将其留在上下文中。

【问题讨论】:

    标签: objective-c string-concatenation


    【解决方案1】:

    在 Objective-C 中,stringWithFormat 方法用于格式化字符串:

    NSString *formattedString = [NSString stringWithFormat:@"C%d", length];
    [someArray insertObject:formattedString];
    

    在 Objective-C 中创建自己的格式化字符串通常更容易,因为如您所见,调用可能相当冗长!

    【讨论】:

    • 谢谢!我认为可能是必须在自己的行上格式化字符串。
    • 您不必这样做(您可以嵌套调用)- 我会说这样做会使代码的可读性稍差一些。请注意,这只是我的看法。
    猜你喜欢
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    相关资源
    最近更新 更多