繁体   English   中英

Objective-C中的字符串操作

[英]String manipulation in objective-c

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

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

之所以采用字符串格式,是因为由于应用程序中的各种格式化原因,我不得不将其从十六进制反弹到int到string。

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

//... 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{
//...

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

//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 nissanCode0.1 [4298:207] 731 2011-06-19 16:18:54.616 nissanCode0.1 [4298:207] 79043536 2011-06-19 16:18:54.617 nissanCode0.1 [4298:207] 79043536 2011-06-19 16:18:54 nissanCode0.1 [4298:207]你好来自formatMyNumber方法

是否可以用整数形式而不是字符串形式的数字? 如果是这样,则很容易使用[NSString stringWithFormat:@"%04d", number] 请参阅此处以获取可能的格式说明符列表。

至于字符串前面的零个数,有两种方法可以做到这一点。 我建议:

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

看看stringWithFormat:可以做什么。 我知道您提到过您的数字是NSStrings,但是如果它们是整数,或者将它们转换回整数,则可以使用以下技巧。 修改以下内容以最适合您的需要:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM