⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stringplus.pas

📁 delphi:字符串处理函数包 很强的字符串处理包
💻 PAS
📖 第 1 页 / 共 3 页
字号:
(*
 * Copyright 1997-2005 Markus Hahn 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *)

{
  (wide) string support routines
}

unit StringPlus;

{$Q-}

interface
uses Windows,
     Classes;


// simple string keeper (readonly)
type
  TStringKeeper = class
  private
    // members
    m_sCnt    : String;
    m_sSubCnt : String;

  public
    // constructor
    // -> the string to keep
    // -> subcontent string (optional)
    constructor Create(const sCnt : String = '';
                       const sSubCnt : String = '');

    // gets the content
    // <- the string
    function Get : String;

    // sets the content
    // -> the string
    procedure SetCnt(const sCnt : String);

    // gets the sub content
    // <- the subcontent string
    function GetSubCnt : String;

    // sets the sub content
    // -> the subcontent string
    procedure SetSubCnt(const sSubCnt : String);
  end;




// the class for holding the functions
type
  TStrPlus = class
  public

    // returns the last character of a string, does not check for empty strings
    // -> string
    // <- last character
    class function GetLastChar(const sTheStr : String) : Char;

    // deletes a string before setting its length to zero
    // -> the string to clear
    // -> length of the string can be provided for faster exexution
    class procedure ClearString(var sTheStr : String;
                                nStrLen : Integer = -1);

    // converts an (unsigned) integer value into a decimal string
    // -> integer value
    // <- decimal string
    class function DecToStr(nValue : Integer) : String;

    // converts a string into an (unsigned) integer
    // -> string to convert
    // -> where to but the integer value
    // <- True: conversion succeeded / False: illegal characters
    class function StrToDec(const sInput : String;
                            var nOutput : Integer) : Boolean;

    // creates a string of a user defined length containing random characters,
    // suitable for file renaming
    // -> desired length
    // <- random string
    class function RandomStr(nLen : Integer) : String;

    // creates a string with a defined number of a single character
    // -> the character
    // -> number of times to repeat
    // <- string
    class function MulChar(const cValue : Char;
                           nLen : Integer) : String;

    // converts a string with binary definitions ('\xx' with xx as an 8bit hex
    // and '\' for a single '\') to a real string
    // -> string to parse
    // -> where to return the real string
    // <- length of the password (-1 equals an error)
    class function GetBinStr(const sSrc : String;
                             var sDest : String) : Integer;

    // creates a relative path from an absolute path
    // -> absolute path
    // <- relative path
    class function RelativePath(const sAbsPath : String) : String;

    // converts a path to a string without an ending '\'
    // -> raw path
    // <- filtered path
    class function PurePath(const sPath : String) : String;

    // converts a path to an RTL (Ready To Link) path, if necessary
    // -> raw path
    // <- RTL path
    class function RTLPath(const sPath : String) : String;

    // tries its best to convert a short filename (plus path) into a long one
    // -> short file name
    // <- long file name
    class function LongFileName(const sShortName : String) : String;

    // converts a memory block of bytes in a hex string representation
    // -> pointer to the memory block
    // -> number of bytes to represent
    // -> separating character (ignored if zero)
    // <- hex string representation
    class function BytesToHexStr(pData : Pointer;
                                 nNumOfBytes : Integer;
                                 cSeparator : Char = #0) : String;

    // converts a string with hex values back to bytes, the string must _not_
    // contain any seperators
    // -> source string
    // -> where to copy the bytes
    // <- number of converted bytes (-1 equals an error)
    class function HexStrToBytes(const sSource : String;
                                 pData : Pointer) : Integer;

    // check if a string is a valid binhex representation
    // -> the string to check
    // -> demanded binary size (-1 equals "don't care")
    // <- True: valid / False: invalid
    class function IsBinHexStr(const sCheckThis : String;
                               nMustBinLen : Integer = -1) : Boolean;

    // returns a complete formatted heap status information string,
    // mainly usable for debugging purposes
    // <- heap status information string
    class function GetHeapStatusInfo : String;

    // creates a version string in the "x.xx.xxx ADDON" format
    // -> major version number
    // -> minor version number (ignored if -1)
    // -> build number (ignored if -1 or nMinor equals -1)
    // -> additional version information
    class function VersionFormat(nMajor : Integer;
                                 nMinor : Integer = -1;
                                 nBuild : Integer = -1;
                                 const sAddOn : String = '') : String;

    // creates a version string in the "x.xx.xx.xxx ADDON" format
    // -> major version number
    // -> minor version number (ignored if -1)
    // -> subminor version number (ignored if -1)
    // -> build number (ignored if -1 or nMinor equals -1)
    // -> additional version information
    class function VersionFormatEx(nMajor : Integer;
                                   nMinor : Integer = -1;
                                   nSubMinor : Integer = -1;
                                   nBuild : Integer = -1;
                                   const sAddOn : String = '') : String;

    // converts a string into a wide string
    // -> 8bit string
    // <- wide string
    class function StringToWideString(const sASCIIStr : String) : WideString;

    // converts file attributes to a uppercase string
    // -> the attributes
    // <- the string representation
    class function FileAttrToStr(lAttributes : WORD32) : String;

    // extracts the extension from a file
    // -> the filename
    // <- the extension (may be empty)
    class function ExtractFileExtension(const sFileName : String) : String;

    // splits a string which is seperated by a special character
    // -> the string to split
    // -> splitting character
    // <- the seperated strings (caller must destroy the list)
    class function StringSplit(const sSource : String;
                               cSplitter : Char) : TStringList;

    // converts an IP address to a string, doesn't check for invalid adresses
    // -> the IP address
    // -> True: big endian / False: little endian format
    // <- the strin representation in the xxx.xxx.xxx.xxx format (decimal)
    class function IPAddrToStr(lIPAddr : WORD32;
                               blBigEndian : Boolean) : String;


    // filters illegal characters (< 32) out of a string
    // -> the string to clean
    // -> True: don't filter #13, #10 / False: filter all
    // <- the filtered string
    class function FilterIllegalChars(const sDirtyStr : String;
                                      blAllowLineBreaks : Boolean) : String;

    // replaces substrings
    // -> the source string
    // -> the string to replace
    // -> the new string
    // <- replaced string
    class function Replace(const sSource : String;
                           const sThis : String;
                           const sThat : String) : String;

    // gets the root of an absolute path
    // -> absolute path
    // <- root
    class function RootPath(const sPath : String) : String;

    // checks if the system supports unicode
    // <- True: Unicode supported / False: ASCII only
    class function IsUnicodeOS : Boolean;

    // compares if a substring is contained from the beginning (case sens.)
    // -> the substring
    // -> the string to search in
    // -> number of characters to compare
    // <- True: substring is in the string at the beginning
    class function CompareFromBegin(const sSub : String;
                                    const sMain : String;
                                    nToCmp : Integer) : Boolean;

    // compares if a substring is contained at the end
    // -> the substring
    // -> the string to search in
    // -> True: case sensitive / False: case insensitive
    // <- True: substring is in the string at the end
    class function CompareFromEnd(const sSub : String;
                                  const sMain : String;
                                  blCaseSensitive : Boolean) : Boolean;

    // tries to get the parent path of a given one (doesn't check if this path
    // exists or the original path is valid, of course)
    // -> the path to go up
    // <- the parent path (may be empty, if it doesn't exist), pure
    class function ParentPath(const sPath : String) : String;

    // stores a stringlist into a single string
    // -> the list to store
    // -> the separating character
    // <- the string
    class function ListToStr(theList : TStringList;
                             cSeparator : Char = ',') : String;

    // expands a single string to a stringlist
    // -> the string to expand
    // -> the separating character
    // -> True: trim the extracted entries / False: do not touch
    // <- string list
    class function StrToList(const sTheStr : String;
                             cSeparator : Char = ',';
                             blTrim : Boolean = True) : TStringList;


    // creates a temporary filename
    // -> path where the temporary file should be created
    // -> some prefix
    // <- temporary file name (given path included!)
    class function MakeTempFileName(const sPath : String;
                                    const sPrefix : String = '') : String;

    // extract concatenated zero terminated strings, terminated with another #0
    // -> pointer to the first C string
    // <- extracted strings
    class function ExtractCStrings(pRawList : Pointer) : TStringList;

    // dumps binary content in a debugger-like memory view
    // -> data to show
    // -> number of bytes
    // -> bytes per line (-1 for default)
    // <- multi-line dump
    class function HexDump(
        data : Pointer;
        nNumOfBytes : Integer;
        nBytesPerLine : Integer = -1) : String;

    // BASE64 encodes binary data
    // -> data to encode
    // -> number of bytes
    // <- encoded string
    class function Base64Encode(
        pRaw : Pointer;
        nLen : Integer) : String;

    // BASE64 decodes a string
    // -> string to decode
    // -> where to put the number of decoded bytes (on success)
    // <- decoded bytes, must be released calling FreeMem(), always zero
    //    terminated (without extra the #0 being counted); Nil on error
    class function Base64Decode(
        const sEnc : String;
        var vnLen : Integer) : PChar;

  end;


implementation
uses SysUtils, FileCtrl;


// internal stuff
var
  versionInfo         : TOSVersionInfo;
  _blUnicodeSupported : Boolean;



//////////////////////////// TStringKeeper ////////////////////////////


constructor TStringKeeper.Create(const sCnt : String = '';
                                 const sSubCnt : String = '');
begin
  SetCnt(sCnt);
  SetSubCnt(sSubCnt);
end;

function TStringKeeper.Get : String;
begin
  Result:=m_sCnt;
end;

procedure TStringKeeper.SetCnt(const sCnt : String);
begin
  m_sCnt:=sCnt;
end;

function TStringKeeper.GetSubCnt : String;
begin
  Result:=m_sSubCnt;
end;

procedure TStringKeeper.SetSubCnt(const sSubCnt : String);
begin
  m_sSubCnt:=sSubCnt;
end;



//////////////////////////// TStrPlus ////////////////////////////


class function TStrPlus.GetLastChar(const sTheStr : String) : Char;
var
  nLen : Integer;
begin
  nLen:=Length(sTheStr);
  if (nLen = 0) then
    Result:=#0
  else
    Result:=sTheStr[Length(sTheStr)];
end;


class procedure TStrPlus.ClearString(var sTheStr : String;
                                     nStrLen : Integer = -1);
begin
  if (nStrLen = -1) then
    nStrLen:=Length(sTheStr);
  FillChar(sTheStr[1], nStrLen, 0);
  (PInteger(@nStrLen))^:=0; // trust no one, not even the compiler :)
  sTheStr:='';
end;



class function TStrPlus.DecToStr(nValue : Integer) : String;
var
  nRest : Integer;
begin
  Result:='';
  repeat
    nRest:=nValue mod 10;
    nValue:=nValue div 10;
    Result:=Concat(Char(Ord('0') + nRest), Result);
  until (nValue = 0);
end;



class function TStrPlus.StrToDec(const sInput : String;
                                 var nOutput : Integer) : Boolean;
var
  blDone : Boolean;
  nPos   : Integer;
  nMulti : Integer;
begin
  // assume error
  Result:=False;

  // avoid special cases
  nPos:=Length(sInput);
  if (nPos = 0) then
    Exit;
  if (nPos > 1) and (sInput[1] = '0') then
    Exit;
  nMulti:=1;
  nOutput:=0;
  blDone:=False;
  while (not blDone) do begin

    // illegal character?
    if (sInput[nPos] < '0') or (sInput[nPos] > '9') then begin
      blDone:=True;
    end
    else begin
      nOutput:=nOutput + (Ord(sInput[nPos]) - Ord('0')) * nMulti;
      nMulti:=(nMulti shl 3) + (nMulti shl 1);  // (faster than "nMulti * 10")
      Dec(nPos);
      if (nPos = 0) then begin
        blDone:=True;
        Result:=True;
      end;
    end;
  end;
end;



class function TStrPlus.RandomStr(nLen : Integer) : String;
const
  RND_SET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
begin
  SetLength(Result, nLen);

  // use all characters from the set above
  while (nLen > 0) do begin
    Result[nLen]:=RND_SET[Random(Length(RND_SET)) + 1];
    Dec(nLen);
  end;
end;


class function TStrPlus.MulChar(const cValue : Char;
                                nLen : Integer) : String;
begin
  SetLength(Result, nLen);
  while (nLen > 0) do begin
    Result[nLen]:=cValue;
    Dec(nLen);
  end;
end;



class function TStrPlus.GetBinStr(const sSrc : String;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -