【问题标题】:Concatenate integers and strings in Objective C在 Objective C 中连接整数和字符串
【发布时间】:2012-12-28 03:56:26
【问题描述】:

请原谅这个问题的简单性。我对 Objective C 完全陌生。

我想知道如何连接整数和字符串值并将它们打印到控制台。

这就是我想要的输出:

10 + 20 = 30

在 Java 中,我会编写这段代码来产生所需的结果:

System.Out.Println(intVarWith10 + " + " + intVarWith20 + " = " + result);

Objective-C 完全不同。我们如何连接这 3 个整数以及它们之间的字符串?

【问题讨论】:

标签: objective-c xcode string integer concatenation


【解决方案1】:

您必须创建一个带有格式的 NSString 并指定数据类型。

类似这样的:

NSInteger firstOperand=10;
NSInteger secondOperand=20;
NSInteger result=firstOperand+secondOperand;
NSString *operationString=[NSString stringWithFormat:@"%d + %d = %d",firstOperand,secondOperand,result];
NSLog(@"%@",operationString);

NSString 格式遵循 C printf 语法

【讨论】:

    【解决方案2】:

    我强烈推荐你这个链接 Objective-C Reference

    Objective-C int 数据类型可以存储正整数或负整数。 int 数据类型可以处理的整数的实际大小或范围取决于机器和编译器的实现。

    所以你可以这样存储。

    int a,b;

    a= 10; b=10;

    那么执行操作需要先了解NSString

    C风格的字符串由单字节字符组成,因此可以存储的字符范围有限。

    int C = a + b; NSString *strAnswer = [NSString stringWithFormat:@"答案 %d + %d = %d", a , b, c];

    NSLog(@"%@",strAnswer)

    希望这会对你有所帮助。

    【讨论】:

      【解决方案3】:

      您可以使用以下代码

      int iFirst,iSecond;
      iFirst=10;
      iSecond=20;
      NSLog(@"%@",[NSString stringWithFormat:@"%d + %d =%d",iFirst,iSecond,(iFirst+iSecond)]);
      

      【讨论】:

        【解决方案4】:

        你可以使用 C 风格的语法,配合 NSLog(如果你只需要打印)

        NSLog(@"%d+%d=%d",intvarWith10,intvarWith20,result);
        

        如果你想要一个字符串变量来保存值

        NSString *str  = [NSString stringWithFormat:@"%d+%d=%d",intvarWith10,intvarWith20,result];
        

        【讨论】:

          【解决方案5】:

          检查以下代码:

          int i = 8;
          NSString * tempStr = [NSString stringWithFormat@"Hello %d",i]; 
          NSLog(@"%@",tempStr);
          

          【讨论】:

            【解决方案6】:

            看看NSString - 它有一个方法stringWithFormat 可以满足您的要求。例如:

            NSString* yString = [NSString stringWithFormat:@"%d + %d = %d",
                                          intVarWith10, intVarWith20 , result];
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-07-18
              • 2016-04-15
              • 2013-10-09
              • 2021-11-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多