Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string with specific charset

Is there a function in Delphi equivalent to Cocoa's stringByTrimmingCharactersInSet?

What I need is to eliminate all the characters included in a charset that are found at the beginning or the end of a string. There can be none, one or more starting or ending the string...

What would be the most efficient way to do this in Delphi?

like image 813
Miguel E Avatar asked Apr 12 '12 10:04

Miguel E


2 Answers

As far i know there is not exist a RTL function like that. But you can check the JclStrings unit part of the JCL project , which include the StrTrimCharsLeft and StrTrimCharsRight functions.

function StrTrimCharsLeft(const S: string; const Chars: TCharValidator): string; overload;
function StrTrimCharsLeft(const S: string; const Chars: array of Char): string; overload;
function StrTrimCharRight(const S: string; C: Char): string;
function StrTrimCharsRight(const S: string; const Chars: TCharValidator): string; overload;
function StrTrimCharsRight(const S: string; const Chars: array of Char): string; overload;
like image 185
RRUZ Avatar answered Sep 21 '22 00:09

RRUZ


To the very best of my knowledge, the RTL does not include such a function. You could use regular expressions to fill the gap:

function MyTrim(const Input: string; const TrimChars: string): string;
begin
  Result := TRegEx.Replace(Input, Format('^[%s]*', [TrimChars]), '');
  Result := TRegEx.Replace(Result, Format('[%s]*$', [TrimChars]), '');
end;

I'm quite sure this is not the best performing solution, but it would be hard to find something much simpler.

like image 44
David Heffernan Avatar answered Sep 21 '22 00:09

David Heffernan