Message Boards Message Boards

GROUPS:

Inserting spaces between specific pairs of letter characters?

Posted 13 days ago
150 Views
|
5 Replies
|
2 Total Likes
|

Hello everyone,

I have many short strings of words that have been joined (no spaces) and where the first character of each word is capitalized (title case), for example, OnTopOfTheWorld. I want to insert spaces in between the words, and the only way I could come up with doing that is by partitioning the strings into characters, identifying the positions of the caps, and inserting a space before each cap. My code looks like this:

str = "OnTopOfTheWorld";
StringTrim[
 StringInsert[str, " ", 
  Flatten[Position[UpperCaseQ /@ StringPartition[str, 1], True]]]]

It works fine, but I thought there might be a more elegant way to do it with StringReplace. Any thoughts?

Greg

5 Replies
Posted 13 days ago

Here is one way

StringSplit["OnTopOfTheWorld", RegularExpression["(?<=[a-z])(?=[A-Z])"]]
(* {"On", "Top", "Of", "The", "World"} *)

To handle more complex cases, take a look at this SE thread.

That certainly works. Thanks! And in StringReplace, can be written as

StringReplace["OnTopOfTheWorld", 
 lowerCaseChar : CharacterRange["a", "z"] ~~ 
   upperCaseChar : CharacterRange["A", "Z"] -> 
  lowerCaseChar ~~ " " ~~ upperCaseChar]

That certainly works. Thanks!

Posted 13 days ago

Another alternative:

StringReplace["OnTopOfTheWorld", RegularExpression["([a-z])([A-Z])"] -> "$1 $2"]

Good stuff. Thanks. I'll have to do my homework on RegEx so that I can switch between Wolfram functions and RegEx.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract