Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I asked this question few days ago: Replace For-loop with functional code

Suppose I use strings instead of lists; for example

a = ToString /@ {123123, 112233};`

I want to insert first end of "4" to every possible position of given string. For elements in a , this give me

b = {4123123, 1423123, 1243123, 1234123, 1231423, 1231243, 1231234, 
     4112233, 1412233, 1142233, 112433, 112343, 1122334} 

Now I Insert second end of "4" to given elements starting at first occurrence of "4". So, I get,

c = {
  44123123, 41423123, 41243123, 41234123, 41231423, 41231243, 41231234,
  14423123, 14243123, 14234123, 14231423, 14231243, 14231234,
  12443123, 12434123, 12431423, 12431243, 12431234, 12344123, ...
}

Is there a method to insert elements into a string without splitting the string into a list of characters, (as done in Mr.Wisard's answer for the same question involving lists. See above link).

This is what I came up with:

a = ToString /@ {123123, 112233};

  Clear[f];
  f[x_] := StringInsert[a, "4", x];
  len = StringLength[
    a[[1]]];(*Every string in set "a" has same length*)
  b = Flatten[Map[f, Range[len + 1]], 1];

  Clear[pos];
  pos[x_] := Flatten[StringPosition[x, "4"], 1][[1]];
  c = Map[pos, b];

  result = {};
  Do[Clear[g];
    g[x_] := StringInsert[b[[i]], "4", x];
    AppendTo[result, Map[g, Range[c[[i]] + 1, 8]]];, {i, 1, Length[b]}

    ];

  Flatten[result] ];

Anny comment to improve this really appreciated.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Similarly to ReplaceList in the last question you can use StringReplaceList here:

StringReplaceList["1234", 
  StartOfString ~~ a___ ~~ b___ ~~ EndOfString :> a <> "0" <> b]
(* {"12340", "12304", "12034", "10234", "01234"} *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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