2017-03-23 95 views
0

我想在不使用StringReplace的情况下替换字符串中的字,任何想法如何?手动字符串替换(免费帕斯卡)

我正在使用4个文本框。

1箱是原文 第二框搜索词 3盒是替代词 4RD盒子的结局文本

var 
    Form1: TForm1; 
    result: string; 
    rep: string; 
    i, iCount: integer; 


procedure TForm1.Button1Click(Sender: TObject); 
begin 
    Edit4.Text := StringReplace(Edit1.Text, Edit2.Text, Edit3.Text, [rfReplaceAll, rfIgnoreCase]); 
    begin 
    result := Edit4.Text; 
    rep := Edit3.Text; 
    iCount := 0; 

    for i := 1 to length(result) do 
    begin 
     if result[i] = rep then 
     inc(iCount); 
    end; 
    end; 
    label5.Caption := ('There was ' + IntToStr(iCount) + ' changes made'); 
end; 
+1

请告诉我们你到目前为止所尝试过的。 –

+1

更新**它似乎并不想用字符串替换函数计数 –

+0

您说:* ...不使用StringReplace *,但您的代码**使用**'StringReplace()'?什么是真正的问题?你想避免'StringReplace()'或者你想要计数替换还是两者? –

回答

1

这应该这样做你想要的:

program mystringreplacetest; 

{$mode objfpc}{$H+} 

uses 
    {$IFDEF UNIX}{$IFDEF UseCThreads} 
    cthreads, 
    {$ENDIF}{$ENDIF} 
    Classes, SysUtils; 


function MyStringReplace(const Input, Find, Replace : String; out Count : Integer) : String; 
var 
    P : Integer; 
begin 
    Count := 0; 

    Result := Input; 

    repeat 
    P := Pos(Find, Result); 
    if P > 0 then begin 
     Delete(Result, P, Length(Find)); 
     Insert(Replace, Result, P); 
     Inc(Count); 
    end; 
    until P = 0; 
end; 


var 
    S : String; 
    Count : Integer; 
begin 
    S := 'a cat another cat end'; 
    S := MyStringReplace(S, 'cat', 'hamster', Count); 
    writeln(S, ' : ', Count); 
    readln; 
end. 

如果这是家庭作业,我已经为你做了几件事:

  • 忽略大小写

  • 避免重复扫描所述字符,直到达到的Find第一次出现。

显然,如果你在Pos功能和DeleteInsert程序以供将来参考读了这将是一件好事。

PS:请注意,此代码包含一个不知情的陷阱。考虑当Replace字符串包含Find(如Find ='cat'和Replace ='catflap')时会发生什么情况。你能看到问题会是什么,以及如何避免它?

+0

你快了:)。我试图在没有代码的情况下制定一个答案,以防万一它是作业,但是编写代码要快得多。干杯! –

+0

这是否回答了您的问题? – MartynA