How to modify a string of symbols based on the positions of $1$'s in a list of Booleans?
Update: A few additional alternatives:
Make list of functions out of exampleInput
:
foo = exampleInput /. {0 -> Identity, 1 -> ToUpperCase};
You can use foo
with StringReplace
or with StringReplacePart
in several ways:
StringReplace[string, "x" ~~ a_ :> "x"<> Last[foo = RotateLeft[foo]][a]]
or (using @J.M.'s regular expression pattern):
StringReplace[string,
RegularExpression["(?![x])[a-z]"] :> Last[foo = RotateLeft[foo]]["$0"]]
or
Block[{i = 1}, StringReplace[string, "x" ~~ a_ :> "x"<> foo[[i++]][a]]]
or
pos = 1 + StringPosition[string, "x"];
StringReplacePart[string, Construct @@@ Thread[{foo, StringTake[string, pos]}], pos]
or
StringReplacePart[string, MapThread[Compose, {foo, StringTake[string, pos]}], pos]
Original answer:
StringRiffle[MapAt[StringReplace["x" ~~ a_ :> "x" <> ToUpperCase[a]],
StringSplit[string, ","], Position[exampleInput, 1]], ","]
"\\xA , \\xB , \\xc , \\xD , \\xe , \\xf , \\xG , \\xh"
Alternatively,
spos = 1 + Pick[StringPosition[string, "x"], exampleInput, 1];
StringReplacePart[string, ToUpperCase[StringTake[string, spos]], spos]
"\\xA , \\xB , \\xc , \\xD , \\xe , \\xf , \\xG , \\xh"
and
ClearAll[stringMapAt]
stringMapAt = StringJoin@MapAt[#, Characters@#2, #3] &;
stringMapAt[ToUpperCase, string, spos[[All, {1}]]]
"\\xA , \\xB , \\xc , \\xD , \\xe , \\xf , \\xG , \\xh"
A variation of the first answer in kglr's post that doesn't deconstruct and reconstruct the list:
Module[{i = 1},
StringReplace[
string, "x" ~~ a_ :> "x" <> If[exampleInput[[i++]] == 1, ToUpperCase@a, a]
]
]
"\\xA , \\xB , \\xc , \\xD , \\xe , \\xf , \\xG , \\xh"
Slightly more verbose but not requiring checking with the If
statement:
Module[{i = 1},
StringReplace[string,
"x" ~~ z_ :> "x" <> FromCharacterCode[First@ToCharacterCode[z] - 32 exampleInput[[i++]]]
]
]
Here's how to use a regex with "negative lookahead" in conjunction with Pick[]
:
With[{pos = Pick[StringPosition[string, RegularExpression["((?![x])[a-z])"]],
exampleInput, 1]},
StringReplacePart[string, ToUpperCase[StringTake[string, pos]], pos]]
"\\xA , \\xB , \\xc , \\xD , \\xe , \\xf , \\xG , \\xh"