![]() |
|
|
|||||||
| Регистрация | << Правила форума >> | FAQ | Пользователи | Календарь | Поиск | Сообщения за сегодня | Все разделы прочитаны |
![]() |
|
|
Опции темы | Поиск в этой теме | Опции просмотра |
|
#1
|
|||
|
|||
|
Здравствуйте, помогите написать функцию замены слов в строке на другие слова, напрмер, дана строка 'one two one three oneone' надо заменить one на zero. Должно получиться: 'zero two zero three oneone'
|
|
#2
|
||||
|
||||
|
Можно разбить строку на слова и заменять слова поотдельности, например так:
Код:
function ReplaceStr(S, Srch, Replace: string; Delim: Char; IgnoreCase: boolean): string;
var
i, l: integer;
tmp: string;
ReplaceFlags: TReplaceFlags;
begin
Result:= '';
l:= Length(S);
if l < 1 then exit;
tmp:= '';
if IgnoreCase then ReplaceFlags:= [rfIgnoreCase] else ReplaceFlags:= [];
for i:= 1 to l do
begin
tmp:= tmp + s[i];
if (s[i] = Delim) or (i = l) then
begin
if Trim(tmp) = Trim(Srch + Delim) then
tmp:= StringReplace(tmp, Srch, Replace, ReplaceFlags);
Result:= Result + tmp;
tmp:= '';
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
x1 = 'one two one three oneone';
x2 = 'one two one three oneone one';
x3 = 'one,two,one,three,oneone';
x4 = 'one, two, one, three, oneone';
var
s: string;
begin
s:= ReplaceStr(x1, 'one', 'zero', ' ', false);
s:= s + #13#10 + ReplaceStr(x2, 'one', 'zero', ' ', false);
s:= s + #13#10 + ReplaceStr(x3, 'one', 'zero', ',', false);
s:= s + #13#10 + ReplaceStr(x4, 'one', 'zero', ',', false);
ShowMessage(s);
end; |
|
#3
|
||||
|
||||
|
StringReplace
|
|
#4
|
||||
|
||||
|
Цитата:
StringReplace заменит строку "one two one three oneone" на "zero two zero three zerozero", а нужно на "zero two zero three oneone". |
|
#5
|
||||
|
||||
|
Код:
StringReplace('one two one three oneone','one ','zero ',[rfReplaceAll])![]() |
|
#6
|
||||
|
||||
|
Цитата:
|
|
#7
|
||||
|
||||
|
Karsh, но если строка будет вида:
"one, two one three oneone one" то не будет работать и твоя функция ![]() |
|
#8
|
|||
|
|||
|
спасибо, братцы!
|
|
#9
|
|||
|
|||
|
спасибо, братцы!
|
|
#10
|
||||
|
||||
|
Aristarh Dark, да, но я хотя бы попытался ответитить на вопрос Cros'а, а не "отписался" бесполезной (в данном вопросе) функцией.
Главная идея это разбить строку на слова. А мою функцию можно использовать как пример для создания более универсальной функции, которая будет учитывать различные разделители слов. Хотя бы так: Код:
function ReplaceStr(S, Srch, Replace: string; IgnoreCase: boolean): string;
var
i, l: integer;
tmp: string;
ReplaceFlags: TReplaceFlags;
begin
Result:= '';
l:= Length(S);
if l < 1 then exit;
tmp:= '';
if IgnoreCase then ReplaceFlags:= [rfIgnoreCase] else ReplaceFlags:= [];
for i:= 1 to l do
begin
if (s[i] in [' ', ',', '.', ':']) or (i = l) then
begin
if i = l then tmp:= tmp + s[i];
if (Trim(tmp) = Trim(Srch)) then
tmp:= StringReplace(tmp, Srch, Replace, ReplaceFlags);
if i < l then tmp:= tmp + s[i];
Result:= Result + tmp;
tmp:= '';
end else tmp:= tmp + s[i];
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
x1 = 'one two one three oneone';
x2 = 'one two one three oneone one';
x3 = 'one,two,one,three,oneone';
x4 = 'one, two, one, three, oneone';
x5 = 'one, two one three oneone one';
var
s: string;
begin
s:= ReplaceStr(x1, 'one', 'zero', false);
s:= s + #13#10 + ReplaceStr(x2, 'one', 'zero', false);
s:= s + #13#10 + ReplaceStr(x3, 'one', 'zero', false);
s:= s + #13#10 + ReplaceStr(x4, 'one', 'zero', false);
s:= s + #13#10 + ReplaceStr(x5, 'one', 'zero', false);
ShowMessage(s);
end; |
|
#11
|
||||
|
||||
|
Я не отписался, а задал направление поиска.
А на счет разбиения на слова, я уже как-то выкладывал на форум свои функции подсчета количества слов и получения слова по его индексу из строки. Вопрос только в поиске. |
|
#12
|
||||
|
||||
|
Попробуй так:
Код:
uses StrUtils; var f,r :AnsiString; begin f:='one'; r:='zero'; // ищем в самом начале строки if AnsiStartsStr(f,Edit1.Text) then Edit2.Text:=StringReplace(Edit1.Text,f,r,[]); // ищем внутри строки без запятой if AnsiContainsStr(Edit2.Text, ' '+f+' ') then Edit2.Text:=StringReplace(Edit2.Text,' '+f+' ',' '+r+' ',[rfReplaceAll]); // ищем внутри строки с запятой if AnsiContainsStr(Edit2.Text, ' '+f+', ') then Edit2.Text:=StringReplace(Edit2.Text,' '+f+', ',' '+r+', ',[rfReplaceAll]); // ищем в конце строки if AnsiContainsStr(Copy(Edit2.Text,Length(Edit2.Text)-Length(f),Length(f)+1), ' '+f) then Edit2.Text:=StuffString(Edit2.Text,Length(Edit2.Text)-Length(f)+1,Length(f),r); Последний раз редактировалось Yurk@, 05.03.2009 в 22:32. |