简体   繁体   English

在 Delphi 中使用 TRegEx 交换字符

[英]Swapping characters using TRegEx in Delphi

I need to swap character dot with comma and vice versa simultaneously.我需要同时用逗号交换字符点,反之亦然。

function TformMain.SwapString(input, fromSymbol, toSymbol: String): String;
begin
  Result := AnsiReplaceStr(input, fromSymbol, '_');  //100,200_00
  Result := AnsiReplaceStr(Result, toSymbol, fromSymbol); //100.200_00
  Result := AnsiReplaceStr(Result, '_', toSymbol); //100.200,00
end;

How to do this using TRegEx in Delphi Rio?如何在 Delphi Rio 中使用 TRegEx 来做到这一点?

Although this is not an answer to your question (how to do this using regular expressions), I'd like to point out that this task can be performed with much greater runtime performance using a simple loop:尽管这不是您问题的答案(如何使用正则表达式执行此操作),但我想指出,可以使用简单循环以更高的运行时性能执行此任务:

function SwapPeriodComma(const S: string): string;
var
  i: Integer;
begin
  Result := S;
  for i := 1 to S.Length do
    case S[i] of
      '.':
        Result[i] := ',';
      ',':
        Result[i] := '.';
    end;
end;

This is much faster than both the AnsiReplaceStr approach and the regular expression approach.这比AnsiReplaceStr方法和正则表达式方法快得多。

Generalised to any two characters:推广到任意两个字符:

function SwapChars(const S: string; C1, C2: Char): string;
var
  i: Integer;
begin
  Result := S;
  for i := 1 to S.Length do
    if S[i] = C1 then
      Result[i] := C2
    else if S[i] = C2 then
      Result[i] := C1;
end;

(If you are OK with a procedure instead of a function, you can do this in-place and save memory and gain speed. But most likely you don't need such optimisations.) (如果您对过程而不是函数感到满意,则可以就地执行此操作并节省内存并提高速度。但很可能您不需要此类优化。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM