How to insert character in all possible positions of a string?
delphi
Solution
This works:
procedure TForm4.Button1Click(Sender: TObject);
var
S: string;
N: integer;
Marker: cardinal;
MaxMarker: cardinal;
Str: string;
i: Integer;
begin
S := Edit1.Text;
N := length(S);
Marker := 0;
MaxMarker := 1 shl (N - 1) - 1;
Memo1.Clear;
Memo1.Lines.BeginUpdate;
for Marker := 0 to MaxMarker do
begin
Str := S[1];
for i := 2 to N do
begin
if (Marker shr (N-i)) and 1 <> 0 then
Str := Str + '-';
Str := Str + S[i];
end;
Memo1.Lines.Add(Str);
end;
Memo1.Lines.EndUpdate;
end;
As you can see, it works by using binary representation of numbers:
t e s t
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Problem
I want to insert a char into every possible position of s string except start and end. e.g. ``` abc I want to have a-bc ab-c a-b-c ``` Below is my test, but not correct: ``` procedure TForm1.Button2Click(Sender: TObject); var start, i,j,k,position,loop: integer; laststart,lastend:integer; c,item,stem:string; str, prefix:string; begin str:='abcd'; memo1.clear; memo1.Lines.Add(str); laststart:=0; lastend:=memo1.lines.count-1; position:=0; prefix:=''; loop:=0; while loop<=length(str)-1 do begin for j:= laststart to lastend do begin item:=memo1.lines[j]; for k:=length(item) downto 1 do begin if item[k]='-' then begin position:=j; break; end; end; //for k prefix:=copy(item,1,position); stem:=copy(item,position+1, length(item)); for start:=1 to length(stem)-1 do begin c:=prefix+copy(stem,1,start)+'-'+ copy(stem, start+1,length(stem)); memo1.lines.add(c); end; end; //for j laststart:=lastend+1; lastend:=memo1.Lines.Count-1; inc(loop); end; //end while end; ``` it outputs: ``` abcd a-bcd ab-cd abc-d a--bcd // not correct a-b-cd a-bc-d ab--cd //incorrect ab-c-d abc--d //incorrect a--bc-d //incorrect ``` I feel the maximum possible breaks is lenth(str)-1, abc->most possible is insert 2 '-' (twice). Is this correct? And are there other faster ways to do it? Thanks a lot.