LoginSignup
0
1

More than 5 years have passed since last update.

c++ builder XE4, 10.2 Tokyo > String > 複数行Stringを降順にする

Last updated at Posted at 2016-04-29
動作確認
C++ Builder XE4
RAD Studio 10.2 Tokyo Update 2 (追記: 2017/12/27)
1\r\n
2\r\n
3\r\n

という<CR><LF>終端の複数行文字列を以下のように降順にする。

3\r\n
2\r\n
1\r\n
Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <memory>
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    String res;

    res = res + L"1:\r\n";
    res = res + L"2:\r\n";
    res = res + L"3:\r\n";

    String strrev = getStringInReverseOrder(res);

    ShowMessage(strrev);
}
//---------------------------------------------------------------------------

String __fastcall TForm1::getStringInReverseOrder(String srcstr)
{
    // <CR><LF>終端の複数行文字列を降順にする

    std::unique_ptr<TStringList> sl(new TStringList);
    sl->StrictDelimiter = true;
    sl->Delimiter = L'\n'; // <LF>を改行識別に使う
    String srcstrWithoutCR = StringReplace(srcstr, L"\r", L"", TReplaceFlags()<<rfReplaceAll);
    sl->DelimitedText = srcstrWithoutCR; // 余分な<CR>は除去

    String dststr;
    for(int idx=sl->Count - 1; idx>=0; idx--) {
        dststr = dststr + sl->Strings[idx] + L"\r\n";
    }

    int pos = dststr.Pos(L"\r\n");
    if (dststr.Pos(L"\r\n") == 1) { // 先頭の改行を除去
        dststr = dststr.SubString(3, MAXINT); // MAXINT:最後まで
    }

    return dststr;
}

元のString文字列の最後が空行の時の処理がいまいち。
時間が確保できないので、ここまで。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1