Separate string at upper case letters using StringReplace
Simply use the pattern Except[WordBoundary, t_?UpperCaseQ]
as the pattern to be replaced:
sR = StringReplace[Except[WordBoundary, t_?UpperCaseQ] :> " " <> t];
sR["AbcDefGhi"]
"Abc Def Ghi"
sR["DistrictOfColumbia"]
"District Of Columbia"
sR["A B C"]
"A B C"
How about using StringSplit
in combination with Riffle
?
f[x_String] := StringJoin[Riffle[StringSplit[x, s_?UpperCaseQ :> s], {"", " "}]];
f["AbcDefGhi"]
f["DistrictOfColumbia"]
"Abc Def Ghi"
"District Of Columbia"
Unfortunately, it also does
f["A B C"]
"A B C"
So maybe this comes closer to your requirements:
g = StringReplace[
RuleDelayed[
Repeated[s : Except[WhitespaceCharacter]] ~~ (t__?UpperCaseQ),
StringRiffle[Join[{s}, Characters[t]]]
]
];
g["AbcDefGhiAAA"]
g["DistrictOfColumbia"]
g["AbcDefGhi"]
g["DistrictOfColumbia"]
g["A B C"]
""Abc Def Ghi A A A""
"District Of Columbia"
"A B C"
Note that without s : Except[WhitespaceCharacter]
, the latter would have been "A B C"
.
What about?:
StringTrim @ StringReplace["AbcDefGhi", t_?UpperCaseQ :> " " <> t]