2011-09-06 92 views
7

在objective-c中將諸如「ThisStringIsJoined」之類的字符串轉換爲「This String Is Join」的最有效方法是什麼?以大寫字母插入或拆分字符串objective-c

我從一個Web服務接收到這樣的字符串,這些字符串超出了我的控制範圍,我想向用戶顯示數據,因此我只想通過在每個大寫字詞的前面添加空格來整理它。字符串總是用大寫字母開頭的每個單詞格式化。

我很新的Objective-C所以不能真正把這一個。

感謝

+0

可能重複:HTTP://計算器。com/questions/1588205/how-to-split-a-string-with-the-upper-character-in-iphone – 0x8badf00d

回答

34

的一種方法如下:

NSString *string = @"ThisStringIsJoined"; 
NSRegularExpression *regexp = [NSRegularExpression 
    regularExpressionWithPattern:@"([a-z])([A-Z])" 
    options:0 
    error:NULL]; 
NSString *newString = [regexp 
    stringByReplacingMatchesInString:string 
    options:0 
    range:NSMakeRange(0, string.length) 
    withTemplate:@"$1 $2"]; 
NSLog(@"Changed '%@' -> '%@'", string, newString); 

在這種情況下,輸出將是:

'ThisStringIsJoined' -> 'This String Is Joined' 

你可能想你自己的需要來調整正則表達式。你可能想把它變成NSString的一個類別。

+0

謝謝,它的效果很好 – Craigt

+1

@aLevelOfIndirection謝謝,這就像一個魅力 – death7eater

+0

我可以添加什麼這裏排除在縮寫之間添加空格?像HelloHTML Goodbye應該產生Hello HTML Goodbye? – userx

-1

你可以嘗試做一個新的字符串,它是原始字符串的小寫副本。然後比較兩個字符串,並在字符不同的地方插入空格。

使用NSString方法轉爲小寫。實現這一目標的

- (NSString *)lowercaseString 
9

NSRegularExpression s爲的路要走,但瑣事,NSCharacterSet也可能是有用的:

- (NSString *)splitString:(NSString *)inputString { 

    int index = 1; 
    NSMutableString* mutableInputString = [NSMutableString stringWithString:inputString]; 

    while (index < mutableInputString.length) { 

     if ([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[mutableInputString characterAtIndex:index]]) { 
      [mutableInputString insertString:@" " atIndex:index]; 
      index++; 
     } 
     index++; 
    } 

    return [NSString stringWithString:mutableInputString]; 
} 
+0

優秀的解決方案! – user523234

+0

有沒有人檢查RegularExpression解決方案是否比這個更慢? – Daniel

1

這裏有一個NSString的類別,將做你想要的。這將處理非ASCII字母。它也將正確分割「IDidAGoodThing」。

@implementation NSString (SeparateCapitalizedWords) 

-(NSString*)stringBySeparatingCapitalizedWords 
{ 
    static NSRegularExpression * __regex ; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     NSError * error = nil ; 
     __regex = [ NSRegularExpression regularExpressionWithPattern:@"[\\p{Uppercase Letter}]" options:0 error:&error ] ; 
     if (error) { @throw error ; } 
    }); 

    NSString * result = [ __regex stringByReplacingMatchesInString:self options:0 range:(NSRange){ 1, self.length - 1 } withTemplate:@" $0" ] ; 
    return result ; 
} 

@end 
1

這是Swift Code(由webstersx提供的客觀c代碼),謝謝!

var str: NSMutableString = "iLoveSwiftCode" 

     var str2: NSMutableString = NSMutableString() 

     for var i:NSInteger = 0 ; i < str.length ; i++ { 

      var ch:NSString = str.substringWithRange(NSMakeRange(i, 1)) 
      if(ch .rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()).location != NSNotFound) { 
      str2 .appendString(" ") 
      } 
      str2 .appendString(ch) 
     } 
     println("\(str2.capitalizedString)") 

    } 

輸出:我愛Swift代碼

+0

如果輸入字符串以大寫字符開頭,則會添加前導空格。 – alexkent

0

對於任何人誰來到這裏尋找類似問題斯威夫特回答: 也許更清潔的(增加Sankalp的答案),以及更多的'SWIFTY「的方法:

func addSpaces(to givenString: String) -> String{ 
    var string = givenString 

    //indexOffset is needed because each time replaceSubrange is called, the resulting count is incremented by one (owing to the fact that a space is added to every capitalised letter) 
    var indexOffset = 0 
    for (index, character) in string.characters.enumerated(){ 
     let stringCharacter = String(character) 

     //Evaluates to true if the character is a capital letter 
     if stringCharacter.lowercased() != stringCharacter{ 
      guard index != 0 else { continue } //"ILoveSwift" should not turn into " I Love Swift" 
      let stringIndex = string.index(string.startIndex, offsetBy: index + indexOffset) 
      let endStringIndex = string.index(string.startIndex, offsetBy: index + 1 + indexOffset) 
      let range = stringIndex..<endStringIndex 
      indexOffset += 1 
      string.replaceSubrange(range, with: " \(stringCharacter)") 
     } 
    } 
    return string 
} 

你調用該函數,像這樣:

var string = "iLoveSwiftCode" 
addSpaces(to: string) 
//Result: string = "i Love Swift Code" 

或者,如果你喜歡的擴展名:

extension String{ 
    mutating func seperatedWithSpaces(){ 
     //indexOffset is needed because each time replaceSubrange is called, the resulting count is incremented by one (owing to the fact that a space is added to every capitalised letter) 
     var indexOffset = 0 
     for (index, character) in characters.enumerated(){ 
      let stringCharacter = String(character) 

      if stringCharacter.lowercased() != stringCharacter{ 
       guard index != 0 else { continue } //"ILoveSwift" should not turn into " I Love Swift" 
       let stringIndex = self.index(self.startIndex, offsetBy: index + indexOffset) 
       let endStringIndex = self.index(self.startIndex, offsetBy: index + 1 + indexOffset) 
       let range = stringIndex..<endStringIndex 
       indexOffset += 1 
       self.replaceSubrange(range, with: " \(stringCharacter)") 
      } 
     } 
    } 
} 

呼叫從一個字符串的方法:

var string = "iLoveSwiftCode" 
string.seperatedWithSpaces() 
//Result: string = "i Love Swift Code" 
相關問題