We are looking for the position of the given substring in the string, indicating what count the found pattern should be, if it occurs several times in the string. The function is case sensitive.
1 2 3 4 5 6 7 8 9 |
var sourceString, findStr: string; position: integer; begin sourceString:= 'text_text_text'; findStr:= '_'; position:= searchPosString(findStr, sourceString, 2); ShowMessage(IntToStr(position)); end; |
Options
sourceString - the string in which we are looking
findStr - the substring we are looking for
Result
The position of the desired substring if the specified parameters match. Or (0) if the specified occurrence number does not exist or the substring was not found at all.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function searchPosString(const findStr, sourceString: string; num: Integer): Integer; var firstSym: PChar; function myPos(const FindStr, SourceString: PChar; num: Integer): PChar; begin Result := AnsiStrPos(SourceString, FindStr); if (Result = nil) then Exit; Inc(Result); if num = 1 then Exit; if num > 1 then Result := myPos(FindStr, Result, num - 1); end; begin firstSym := PChar(SourceString); Result := myPos(PChar(FindStr), PChar(SourceString), num) - firstSym; if Result < 0 then Result := 0; end; |