我知道这可以用 NSScanner 完成,但我希望有人有现成的解决方案。
干得好:
NSString *chopString = stringToSplit.copy; /// @"stringToSplit" Goes Here
NSString *resultingString;
NSCharacterSet *capsSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
while (chopString.length > 0) {
/// Pull the first character out each time ///
/// Since it may trigger the Scanner ///
NSString *firstChar = [chopString stringByReplacingCharactersInRange:(NSRange){1, chopString.length-1} withString:@""];
chopString = [chopString stringByReplacingCharactersInRange:(NSRange){0,1} withString:@""];
/// Scan up to the next Capital letter ///
NSString *upToString;
NSScanner *chopScanner = [NSScanner scannerWithString: chopString];
[chopScanner scanUpToCharactersFromSet:capsSet intoString:&upToString];
/// Feed first character and scan results into string ///
/// Separated by a space ///
if (!resultingString)
resultingString = [NSString stringWithFormat:@"%@%@",firstChar,upToString];
else
resultingString = [NSString stringWithFormat:@"%@ %@%@", resultingString,firstChar,upToString];
/// Chop the remaining string down by the length of the scan ///
chopString = [chopString stringByReplacingCharactersInRange:(NSRange){0,chopScanner.scanLocation} withString:@""];
}
resultingString = [resultingString capitalizedString]; /// @"String To Split" Comes Out!