簡體   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