Insert or split a string in capital letters objective-c

What would be the most efficient way to convert a string like "ThisStringIsJoined" to "This String Is Join" in objective-c?

I get lines from a web service that are out of my control, and I would like to present the data to the user, so I just would like to reduce it a bit by adding spaces before each uppercase word. Lines are always formatted with every word that starts in a capital letter.

I am new to objective-c, so I can't really expose this.

thanks

+7
source share
6 answers

One way to achieve this is to:

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

The output in this case will be:

 'ThisStringIsJoined' -> 'This String Is Joined' 

You might want to customize the regular expression to your own needs. You can do this in a category on NSString.

+34
source

NSRegularExpression is the way to go, but like the little things, NSCharacterSet can also be useful:

 - (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]; } 
+9
source

Here's the NSString category that will do what you want. This will handle non-ASCII letters. It will also correctly share 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
source

Here is the Swift code (target code c from webstersx), thanks!

 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)") } 

Result: I Love Swift Code

+1
source

For everyone who came here, looking for a similar question in Swift: Perhaps a cleaner (addition to Sankalp), and a more “Swifty” approach:

 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 } 

You call the function as follows:

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

Alternatively, if you prefer extensions:

 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)") } } } } 

Call the method from the line:

 var string = "iLoveSwiftCode" string.seperatedWithSpaces() //Result: string = "i Love Swift Code" 
0
source

You can try creating a new line, which is a lowercase copy of the original line. Then compare the two lines and insert spaces wherever characters are different.

Use the NSString method to lowercase.

 - (NSString *)lowercaseString 
-one
source

All Articles