[Switf]下标语法subscript简单举例

来源:互联网 发布:淘宝差评不显示怎么办 编辑:程序博客网 时间:2024/06/02 16:17



import Foundation


extension String{

   subscript( charIndex:Int ) ->String{

   let string = (selfasNSString).substringWithRange(NSMakeRange(charIndex,1))

   return string

    }

}


//十万以下的数

func getYourNumber(string:String) ->Int {

   var sum:Int   =0

   var short:Int =1

    //遍历char

   for var i =0 ; i <count(string) ;i++ {

       switch  string[i] {

       case"" : short =1

       case"" : short =2

       case"" : short =3

       case"" : short =4

       case"" : short =5

       case"" : short =6

       case"" : short =7

       case"" : short =8

       case"" : short =9

       case"" : sum +=  short *10

       case"" : sum +=  short *100

       case"" : sum +=  short *1000

        case"" : sum +=  short *10000 //如果需求大于10w,在此处判断sum的值>10,sum*1w

       default:

           break//``不考虑

        }

        //判断最后一位

       if i ==count(string) -1{

           switch string[count(string)-1] {

           case"" ,"" ,"" ,"":break

           default:

                sum += short

            }

        }

    }

   return sum

}

println(getYourNumber("十一"))

println(getYourNumber("一千零二十"))

println(getYourNumber("三千零一"))

println(getYourNumber("九千九百九十九"))

println(getYourNumber("三千零一十一"))


打印得到

11

1020

3001

9999

3011



类似的,OC实现



int main(int argc,const char * argv[]) {

    

        test(@"");

        test(@"十一");

        test(@"一千零二十");

        test(@"三千零一");

        test(@"九千九百九十九");

        test(@"三千零一十一");

 

   return 0;

}


NSString* test(  NSString *yourString ){

    

    NSArray *numberArray =@[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];

    NSArray *elseNumber  =@[@"",@"",@"",@""];

    NSInteger  sum      =0 ;

    NSInteger  shortSum =1 ;

    

   for( int i =0 ; i < yourString.length ;i++){

        NSString *str        = [yourString substringWithRange:NSMakeRange(i,1)];

       if ([numberArray containsObject:str]) {

            NSUInteger index = [numberArray indexOfObject:str];

            shortSum = index ;

        }

        

       if ([elseNumber containsObject:str]) { //十百千万  10^3 = pow(10, 3)

            NSUInteger otherIndex = [elseNumber indexOfObject:str];

            sum += (NSInteger)pow(10, otherIndex +1) * shortSum ;

        }

        

       //判断末尾的数

       if (i == yourString.length - 1  && [numberArray containsObject:str]) {            sum  += shortSum ;

        }

    }

    NSLog(@"%ld",sum);

   return [NSString stringWithFormat:@"%ld",sum];

}




0 0
原创粉丝点击