2013-10-07 43 views
0

我遇到問題。我的字符串格式爲​​,它有「」。現在我想從​​只得到abc(意味着從字符串中刪除「」,只能得到abc)。我怎樣才能做到這一點?在此先感謝如何從字符串中切割字符串在iOS中有「abc」

+1

你〜應變g以「最後一個字符爲」開始? – incmiko

+0

@incmiko:是的,正確的。 –

+0

我寫了我的答案檢查它 – incmiko

回答

1
#import <Foundation/Foundation.h> 

int main(int argc, const char **argv) { 
    @autoreleasepool { 
     NSString *input = @"\"abc\""; 
     NSArray *elements = [input componentsSeparatedByString:@"\""]; 
     if ([elements count] > 0) { 
      NSString *element = [elements objectAtIndex:1]; 
      NSLog(@"count=%lu element='%@'", [elements count], element); 
     } 
    } 
    return 0; 
} 

$ clang -o strsep strsep.m -framework Foundation 
$ ./strsep 
2013-10-07 11:42:44.274 strsep[34292:707] count=3 element='abc' 
1
[String replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [String length])]; 
2
​​
1

有一個內置的功能,可以讓你用另一個替換字符串的所有出現 - 如果另一個被設置爲空字符串(@ 「」)它將有效地刪除所有出現的子字符串。你的榜樣:

NSString * yourNewString = [yourOldString stringByReplacingOccurrencesOfString:@"\"" withString:@""]); 
1

可以更換的出現。「有空的空間

NSString *some = @"\"abc\""; 
NSLog(@"%@",some); 
NSString *newString = [some stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 
NSLog(@"%@",newString); 
0

我爲你寫的方法,這將很好地工作:(如果你的最後一個字符是」)

- (NSString*) getTheString:(NSString*) yourString{ 
    NSString* answerString = [[NSString alloc]init]; 

    int substrinFrom = 0; 
    for (NSInteger charIdx=0; charIdx<[yourString length]; charIdx++){ 

     if ('"' == [yourString characterAtIndex:charIdx]) { 
      substrinFrom = charIdx; 
      NSLog(@"%i",substrinFrom); 
      break; 
     } 
    } 
    answerString = [yourString substringWithRange:NSMakeRange(substrinFrom+1, [yourString length] - substrinFrom -2)]; 

    return answerString; 

} 

來測試它:

NSString* test = [self getTheString:@"\"Hello this is a test string, and it will work\""]; 
NSLog(@"%@",test);