2014-10-31 64 views
-1

我喜試圖將字符串轉換在Xcode爲int數組中目標C的運行良好,但給一些誤差在編輯http://ideone.com字符串int數組客觀

我有喜歡的輸入= {1,2,3,4 ,5},並希望將其轉換成int數組或NSArray的中和打印....

#import <Foundation/Foundation.h> 

NSArray* sampleMethod(NSString*val){ 
    NSString *stringWithoutbracketstart = [val stringByReplacingOccurrencesOfString:@"{" withString:@""]; 
    NSString *stringWithoutbracketend = [stringWithoutbracketstart 
    stringByReplacingOccurrencesOfString:@"}" withString:@""]; 
    NSLog(@"%@",stringWithoutbracketend); 
    NSArray *items=[[NSArray alloc]init]; 
    items = [stringWithoutbracketend componentsSeparatedByString:@","]; 
    //NSLog(@"%@",items); 
return items; 
} 

int main(int argc, const char * argv[]) { 
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    NSString *value [email protected]"{1,2,3}"; 
    NSArray* ip1= sampleMethod(value); 
    NSLog(@"%@",ip1); 
[pool drain]; 
return 0; 

} 
+0

這個例子在Java?中? – trojanfoe 2014-10-31 10:15:35

+0

我很困惑爲什麼這個鏈接你提供了一些java代碼的鏈接,但你的問題是關於objective-c的問題? – Popeye 2014-10-31 10:17:22

+0

@trojanfoe它屬於Objective C – 2014-10-31 10:20:49

回答

1

爲什麼不把輸入字符串有效的JSON,然後它可以用很少的編碼工作(沒有努力在任意擴展全部關於解析):

int main(int argc, const char **argv) 
{ 
    int retval = 0; 
    @autoreleasepool { 
     if (argc == 2) { 
      NSString *str = @(argv[1]); 
      NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; 
      NSError *error = nil; 
      NSArray *array = [NSJSONSerialization JSONObjectWithData:data 
                  options:0 
                   error:&error]; 
      if ([array isKindOfClass:[NSArray class]]) { 
       // Done 
      } else if (!array) { 
       NSLog(@"Input data is invalid: %@", [error localizedDescription]); 
       retval = 2; 
      } else { 
       NSLog(@"Input data is invalid"); 
       retval = 3; 
      } 
     } else { 
      NSLog(@"Provide a JSON-list"); 
      retval = 1; 
     } 
    } 
    return retval; 
} 

這意味着你將需要提供JSON格式的列表:

$ ./myprog '[ 1, 2, 3 ]' 

(引號是必需的)

+0

感謝您的信息我瞭解差異B/W NSNUMBER和NSARRAY ... – 2014-10-31 11:23:10

+0

@NirbhavGupta我不明白你的意思。 – trojanfoe 2014-10-31 11:23:35

-2

我很容易找到解決方案通過使用你的建議....

#import <Foundation/Foundation.h> 

NSArray*sampleMethod(NSString*val){ 
    NSString *newStr = [val substringFromIndex:1]; 
    NSString *newStr1 = [newStr substringToIndex:[newStr length]-1]; 
    NSArray *yourWords = [newStr1 componentsSeparatedByString:@","]; 
return yourWords; 
} 

int main(int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
     NSString *value [email protected]"{1,2,3}"; 
     NSArray* ip1= sampleMethod(value); 
     NSLog(@"%@",ip1); 
    [pool drain]; 
    return 0; 
}