NSString - 2位数字

时间:2011-05-13 15:33:51

标签: iphone objective-c cocoa-touch ios nsstring

`嗨, 我有一个2位数字(如32)的字符串,但我想得到并使用它作为2个单位数字(如3和2)。我该怎么做?提前致谢。

  NSString *depositOverTotalRwy = [NSString stringWithFormat:@"%@", [deposit text]];
NSArray *components = [depositOverTotalRwy
                       componentsSeparatedByString:@"/"];
NSString *firstThird = [components objectAtIndex:0];
unichar firstChar = [firstThird characterAtIndex: 0];
NSString *firstCharStr = [NSString stringWithFormat:@"%c", firstChar];

unichar secChar = [firstThird characterAtIndex: 1];
NSString *secCharStr = [NSString stringWithFormat:@"%c",secChar];






NSLog(@"%@ over %@", firstCharStr, secCharStr);

if ([firstCharStr  isEqualToString: @"1"]) {
    firstCharStr=@"wet";
    NSLog(@"wet");
}
if ([firstCharStr  isEqualToString: @"2"]) {
    firstCharStr=@"snow";

    NSLog(@"snow");
}
if ([firstCharStr  isEqualToString: @"3"]) {
    firstCharStr=@"ice";
    NSLog(@"ice");
    }

if ([secCharStr  isEqualToString: @"1"]) {
    secCharStr=@"wet";
    NSLog(@"wet");
}
if ([secCharStr  isEqualToString: @"2"]) {
    secCharStr=@"snow";

    NSLog(@"snow");
}
if ([secCharStr  isEqualToString: @"3"]) {
    secCharStr=@"ice";
    NSLog(@"ice");
}

NSString *secThird = [components objectAtIndex:1];
if ([secThird isEqualToString: @"1"]) {
    secThird = @"wet";
    NSLog(@"wet");
}
if ([secThird isEqualToString:@"2"]) {
    secThird = @"snow";

    NSLog(@"snow");
}
if ([secThird isEqualToString:@"3"]) {
    secThird = @"ice";

    NSLog(@"ice");
}

NSString *thirdThird = [components objectAtIndex:2];

if ([thirdThird isEqualToString: @"1"]) {
    thirdThird = @"wet";
    NSLog(@"wet");
}
if ([thirdThird isEqualToString:@"2"]) {
    thirdThird = @"snow";

    NSLog(@"snow");
}
if ([thirdThird isEqualToString:@"3"]) {
    thirdThird = @"ice";

    NSLog(@"ice");
}

dep.text = [NSString stringWithFormat:@"1/3 %@%@ 2/3 %@ 3/3 %@", firstCharStr,secCharStr, secThird, thirdThird];

它现在与数字(即32)一起工作,但如果我试图只放一个数字我得到一个错误....任何想法?感谢

4 个答案:

答案 0 :(得分:2)

NSString的-characterAtIndex:应该可以解决问题:

NSString            *firstThird = @"32";
unichar             c1, c2;

c1 = [ firstThird characterAtIndex: 0 ];
c2 = [ firstThird characterAtIndex: 1 ];

switch ( c1 ) {
case '3':
    ...
}

答案 1 :(得分:1)

循环并从字符串中一次提取一个字符。

for(int i = 0; i < [myString length]; i++)
{
      char extractedChar = [myString characterAtIndex:i];

      if(extractedChar == '1')....
}

答案 2 :(得分:0)

删除任何unicode复杂性,如何提取字符

unichar firstChar = [firstThird characterAtIndex:0];

答案 3 :(得分:0)

NSString *firstThird = [components objectAtIndex:0];//--- I get 32 from this string but i want 3 and 2
NSArray *numbersAsStrings = [firstThird componentsSeparatedByString:@""];
NSMutableArray *digits = [NSMutableArray array];
for (NSString *digit in numbersAsStrings)
{
    [digits addObject:[NSNumber numberWithInt:[digit intValue]]];
}

此示例可以使用任意数字并将其转换为NSNumber s。

的数组

访问:

int int1 = [[digits objectAtIndex:0]intValue]; //returns 3