开发者

Find the last occurrence of char in a string

开发者 https://www.devze.com 2023-03-01 14:57 出处:网络
Does there exist any RTL Delphi function to determine the position of the last occurrence of开发者_高级运维 a char in a string?try the LastDelimiter function which is part of the SysUtils unit.RRUZ an

Does there exist any RTL Delphi function to determine the position of the last occurrence of开发者_高级运维 a char in a string?


try the LastDelimiter function which is part of the SysUtils unit.


RRUZ answered the actual question (he gave you a RTL function).

Still, I cannot quite resist giving a simple code snippet that does what you want:

function LastCharPos(const S: string; const Chr: char): integer;
var
  i: Integer;
begin
  result := 0;
  for i := length(S) downto 1 do
    if S[i] = Chr then
      Exit(i);
end;

Since this does exactly what you want and offer no other features, it is far more compact (especially when we use the Exit(Result) syntax of Delphi 2009 and later) and probably slightly faster. In Delphi 2007, however, you have to do

function LastCharPos(const S: string; const Chr: char): integer;
var
  i: Integer;
begin
  result := 0;
  for i := length(S) downto 1 do
    if S[i] = Chr then
    begin
      result := i;
      break; // or Exit; if you prefer that
    end;
end;


Use StrRScan or AnsiStrRScan, both in the SysUtils unit. The latter, despite its name, works on Unicode characters in the Delphi versions where string is UnicodeString. (If you still need the "real" Ansi version, use the AnsiStrings unit.)

These functions search for exactly one character, whereas LastDelimiter searches for any of several characters from the given list of possibilities — think of StrRScan as LastDelimiter optimized for a one-character Delimiters argument.


The best cross-platform solution is TStringHelper.LastIndexOf, it exists since Delphi XE4.

Note, that this function is 0-based.


And here's my contribution for finding the position of the nth occurrence of a substring within a string.

function GetPositionOfNthOccurence(sSubStr, sStr: string; iNth: integer): integer;
var
  sTempStr: string;
  iIteration: integer;
  iTempPos: integer;
  iTempResult: integer;
begin
  result := 0;

  // validate input parameters
  if ((iNth < 1) or (sSubStr = '') or (sStr = '')) then exit;

  // evaluate
  iIteration := 0;
  iTempResult := 0;
  sTempStr := sStr;
  while (iIteration < iNth) do
  begin
    iTempPos := Pos(sSubStr, sTempStr);
    if (iTempPos = 0) then exit;
    iTempResult := iTempResult + iTempPos;
    sTempStr := Copy(sStr, iTempResult + 1, Length(sStr) - iTempResult);
    inc(iIteration);
  end;
  result := iTempResult;
end;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号