【问题标题】:String manipulation in objective-cObjective-C中的字符串操作
【发布时间】:2011-06-19 03:53:35
【问题描述】:

这很难描述,但我目前正在从数据库中捕获一个字符串,这个字符串可以是 1-4 个字符长,但是我希望始终显示 4 个字符,所以如果我得到一个返回的字符串是 34 ,我希望它是 0034。

我已经设置了一个捕获字符串的方法,所以现在我只需要弄清楚如何做到这一点。然后我打算做的是将该字符串输入到 NSArray 中,这样我就可以将数组的每个 [i'th] 发送到 4 个不同的方法来控制我的应用程序中的动画。

它采用字符串格式的原因是因为应用程序中的各种格式化原因,我不得不将它从十六进制反弹到整数到字符串。

这是我到目前为止的代码。建议/解决方案将非常感谢,我太新了,很难找到字符串操作等问题的解决方案。

//... other method I am getting the string from/.
[self formatMyNumber:dataString];
///..


-(void)formatMyNumber:(NSString *)numberString{
    //resultLabel.text = numberString; //check to make sure  string makes it to here.
    //NSLog(@"hello From formatMyNumber method"); //check
}

//..
//the with send off each character to 4 animation methods that accept integers.
- (void)playAnimationToNumber:(int)number{
//...

//更新...奇怪的事情发生了。 到目前为止,这是我的方法。

//Number Formatter
-(void)formatMyNumber:(NSString *)numberString{


    NSLog(@"This is what is passed into the method%@",numberString);
    int tempInt = (int)numberString;
    NSLog(@"This is after I cast the string to an int %i",tempInt);

    //[NSString alloc] stringWithFormat:@"%04d", numberString];
    NSString *tempString = [[NSString alloc] initWithFormat:@"%04d", tempInt];

    NSLog(@"This is after I try to put zeros infront %@",tempString);

    //resultLabel.text = tempString;
    //NSLog(@"hello From formatMyNumber method");
}

这是输出。

[会议于 2011-06-19 开始 16:18:45 +1200。] 2011-06-19 16:18:54.615 日产代码0.1[4298:207] 731 2011-06-19 16:18:54.616 日产代码0.1[4298:207] 79043536 2011-06-19 16:18:54.617 日产代码0.1[4298:207] 79043536 2011-06-19 16:18:54.617 nissanCode0.1[4298:207] 你好来自 formatMyNumber 方法

【问题讨论】:

    标签: iphone ios nsstring nsarray int


    【解决方案1】:

    就字符串前面的零数量而言,有几种方法可以做到这一点。我建议:

    NSString *myString = [NSString stringWithFormat:@"%04d",[dataString intValue]];

    【讨论】:

    • 像梦一样工作,谢谢 :) 很高兴看到方法的不同并全部尝试,知道现在发生了什么谢谢。
    【解决方案2】:

    你可以用整数形式而不是字符串形式的数字吗?如果是这样,使用[NSString stringWithFormat:@"%04d", number] 非常容易。有关可能的格式说明符列表,请参阅 here。

    【讨论】:

    • 啊酷..这有点像c++..我应该看看,谢谢你现在试试这个:P
    • 这似乎不想工作它扔回没有任何意义的大数字。我尝试了几种方法..但似乎无法让它发挥作用。
    • 你的数字是整数还是浮点数?如果它是浮点数或双精度数,则必须改用 %04f ...阅读我发布的链接。
    • 您在上面提到您将“将其转换为 int”。如果你有一个 NSString 指针,你不能这样做,你只会读取指针值。正如 Dancreek 所说,你必须使用 [myString intValue],或者如果你已经有一个 int 你应该使用它。
    【解决方案3】:

    看看stringWithFormat: 能做什么。我意识到你提到你的数字是 NSStrings,但如果它们是整数,或者你将它们转换回整数,下面可能会奏效。修改以下内容以最适合您的需要:

    return [NSString stringWithFormat:@"%04d", number];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多