Search code examples
c++c++builderrad-studio

Copying text from a Memo by line/index


I was wondering if there is a way to copy text from a specific line of memo. For example, I want to store the content from the 3rd line of my memo to a string, then do some operation on that string and copy it to another memo/edit.

I've tried a few variations of this, but none work:

str_temp = Memo1->Lines[2].Text;
Memo2->Lines->Append(str_temp);

when I ask from Lines[0] it simply copies everything from the memo into the string:

str_temp = Memo1->Lines[0].Text;
Memo2->Lines->Append(str_temp);

Solution

  • The Lines property is a pointer to a TStrings object. So Memo1->Lines[2].Text is the same as doing (*(Memo1->Lines+2)).Text per pointer arithmetic, which is syntaxically valid but logically wrong as it will end up accessing invalid memory. Whereas Memo1->Lines[0].Text is the same as doing (*(Memo1->Lines)).Text (aka Memo1->Lines->Text), which is both legal and valid but is not the result you want.

    TStrings has a Strings[] property, that is what you need to use instead, eg:

    String str_temp = Memo1->Lines->Strings[2];
    

    Alternatively, TStrings has an operator[] that uses Strings[] internally, eg:

    String str_temp = (*(Memo1->Lines))[2];