如何在字符串的所有可能位置插入字符?

时间:2012-05-17 11:58:12

标签: delphi

我想在除了start和end之外的s字符串的每个可能位置插入一个char。 例如

abc
I want to have 
a-bc
ab-c
a-b-c

以下是我的测试,但不正确:

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;

输出:

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

我觉得最大可能的中断是lenth(str)-1,abc-> gt;最可能的是插入2' - '(两次)。这是对的吗?

还有其他更快的方法吗?

非常感谢。

4 个答案:

答案 0 :(得分:9)

递归版。

  procedure InsertSymbols(s: string; c: Char; Position: Integer = 1);
  var
    i: Integer;
  begin
    Memo1.Lines.Add(s);
    for i := Position to Length(s) - 1 do
      InsertSymbols(Copy(s, 1, i) + c + Copy(s, i + 1, Length(s) - i), c, i + 2);
  end;

begin
  InsertSymbols('Test', '-');
end;

答案 1 :(得分:7)

这有效:

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;

Screenshot http://privat.rejbrand.se/markersinstrallpos.png

如您所见,它通过使用数字的二进制表示来工作:

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

答案 2 :(得分:1)

为什么所有困难的解决方案? 只需将字符串复制到char中的新char,在中间添加连字符,最后一个除外。

答案 3 :(得分:1)

我需要分隔一个字符串以用作序列号,这里是代码:

Function GetDashedKey(Key: string): string
const
  PartSize = 7;
var
  Indx: Integer;
  dashedKey : string;
begin

  repeat
    if Trim(dashedKey)<>'' then
      dashedKey := dashedKey + ' - ';

    if Length(Key) < PartSize then
    begin
      dashedKey := dashedKey + Key;
      Key := '';
    end
    else
    begin
      dashedKey := dashedKey + Copy(Key, 1, PartSize);
      Key := Copy(Key, PartSize + 1, Length(Key)-1);
    end;
  until Trim(Key) = '';

  Result := dashedKey;
end;
相关问题