简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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