0

How can I search a dynamic array of char in Delphi 6 for a sub-string and get back an index to a match, not a pointer? I've seen functions in Delphi 6 that do this for strings but not for dynamic char arrays. There is a function called SearchBuf but that function returns a PChar pointer to the match location when what I need is the array index of the match.

Thanks.

3
  • 1
    Any particular reason you're using a dynamic array of characters? I can't think of a single advantage they offer over strings. Commented May 30, 2010 at 4:32
  • I am moving data in out between functions that manage audio data in char array format. It's a legacy code thing. Commented Jun 4, 2010 at 1:32
  • If you set the length of a string variable to the size of your dynamic array, then you can type-cast that string to PChar and you'll have an equally good character array for the function to read or fill. Commented Jun 4, 2010 at 3:04

1 Answer 1

1

If you have a pointer to the match, simply subtract the pointer to the first character, and you'll have your index.

var
  Buf, Result: PChar;
  Index: Integer;

Result := SearchBuf(Buf, ...);
if Assigned(Result) then
  Index := Result - Buf
else
  Index := -1; // not found

I'm pretty sure that pointer arithmetic is allowed in Delphi 6. If not, then type-cast the pointers to integral types first:

Index := Cardinal(Result) - Cardinal(Buf);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.