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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With