5
$\begingroup$

There is a list of strings:

{"x1x2", "x1", "x1x2x3", "x3", "x4", "x1x2x3x4"}

The goal is to insert "&&" between every two elements in a list. I need to get a result:

{"x1&&x2", "x1", "x1&&x2&&x3", "x3", "x4", "x1&&x2&&x3&&x4"}

It's not difficult to do it by hand in this case, but it's not a desirable solution. I found only one function that can help with this task (String Insert []) but it works with indexes and doesn't help to deal with this task. What can I do to solve this problem?

$\endgroup$
  • 1
    $\begingroup$ It looks like it is a part of a bigger problem that might be solved easier. Consider an extended post. I suspect something like en.wikipedia.org/wiki/XY_problem $\endgroup$ – yarchik Dec 9 '19 at 9:50
8
$\begingroup$

This is what you want ?

StringJoin[Riffle[Partition[Characters[#], 2], "&&"]] & /@ {"x1x2", 
  "x1", "x1x2x3", "x3", "x4", "x1x2x3x4"}

(* Out: {"x1&&x2", "x1", "x1&&x2&&x3", "x3", "x4", "x1&&x2&&x3&&x4"} *)

$\endgroup$
  • $\begingroup$ It's exactly what I wanted! Thanks! $\endgroup$ – Rumato Dec 9 '19 at 9:53
8
$\begingroup$
lst = {"x1x2", "x1", "x1x2x3", "x3", "x4", "x1x2x3x4"};

You can use a combination of StringRiffle and StringPartition

StringRiffle[StringPartition[#, 2], "&&"] & /@ lst  

{"x1&&x2", "x1", "x1&&x2&&x3", "x3", "x4", "x1&&x2&&x3&&x4"}

Alternatively, you can use StringReplace:

StringReplace[lst, d : DigitCharacter .. ~~ a : LetterCharacter :> d <> "&&" <> a]

{"x1&&x2", "x1", "x1&&x2&&x3", "x3", "x4", "x1&&x2&&x3&&x4"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.