2012-03-17 20 views
0

複数のレコードを含む文字列を文字列リスト内の個々の項目に分割したいと考えています。Delphi複数のレコードを含む文字列をさまざまな区切り文字で分割します

+ CMGL:0、 "REC UNREAD"、 "+ 27832729407" ,, "12/03/17,21(デルファイ7)

ここでは、単一の長い文字列内の生のテキストであります:32:05 + 08 "これはメッセージ1 + CMGL:1、" REC UNREAD "、" + 27832729407 "、" 12/03/17,21:32:30 + 08 "のテキストです。メッセージ2 + CMGL:2、 "REC UNREAD"、 "+ 27832729407" ,, "12/03/17,21:32:58 + 08"これはメッセージ3 + CMGLのテキストです:3、 "REC UNREAD" 、 "+ 27832729407" ,, "12/03/17,21:33:19 + 08"最後にメッセージ4 + CMGL:4、 "REC UNREAD"、 "+ 27832729407" ,, "12/03/17 、21:34:03 + 08 "もう一度、5番目のメッセージのテキストOKW

私はGSM装置からそれを受け取りました。最後の文字は2文字ですが、私のGSMデバイスからの結果は常にOKです。

+CMGL: 0,"REC UNREAD","+27832729407",,"12/03/17,21:32:05+08"This is the text in message 1 
+CMGL: 1,"REC UNREAD","+27832729407",,"12/03/17,21:32:30+08"And this is the text in message 2 
+CMGL: 2,"REC UNREAD","+27832729407",,"12/03/17,21:32:58+08"This is the text in message 3 
+CMGL: 3,"REC UNREAD","+27832729407",,"12/03/17,21:33:19+08"And finally text in message 4 
+CMGL: 4,"REC UNREAD","+27832729407",,"12/03/17,21:34:03+08"Ok one more the the text in 5th message 

(各+ CGMLは、新しい行の始まりである)

それが均一であるように私はここからそれに取り組むことができます。

これは私が必要との結果です。助けていただければ幸いです。私はこれが理にかなってほしい。

ありがとうございます!

答えて

4

PosExおよびCopy関数を使用して、文字列を分割する関数を作成できます。

チェックこのサンプル

{$APPTYPE CONSOLE} 

uses 
    Classes, 
    StrUtils, 
    SysUtils; 


const 
    GSMMessage= 
    '+CMGL: 0,"REC UNREAD","+27832729407",,"12/03/17,21:32:05+08"This is the text in message 1+CMGL: 1,"REC UNREAD","+27832729407",,"12/03/17,21:32:30+08"And this is the text in message 2+CMGL: 2,"REC UNREAD","+27832729407",,"12/03/17,21:32:58+08"'+ 
    'This is the text in message 3+CMGL: 3,"REC UNREAD","+27832729407",,"12/03/17,21:33:19+08"And finally text in message 4+CMGL: 4,"REC UNREAD","+27832729407",,"12/03/17,21:34:03+08"Ok one more the the text in 5th messageOK'; 


procedure SplitGSMMessage(const Msg : String; List : TStrings); 
const 
StartStr='+CMGL'; 
Var 
FoundOffset : Integer; 
StartOffset : Integer; 
s   : String; 
begin 
    List.Clear; 

    StartOffset := 1; 
    repeat 
     FoundOffset := PosEx(StartStr, Msg, StartOffset); 
     if FoundOffset <> 0 then 
     begin 
     s := Copy(Msg, StartOffset, FoundOffset - StartOffset); 
     if s<>'' then List.Add(s); 
     StartOffset := FoundOffset + 1; 
     end; 
    until FoundOffset=0; 

    // copy the remaining part 
    s := Copy(Msg, StartOffset, Length(Msg) - StartOffset + 1); 
    if s<>'' then List.Add(s); 
end; 

var 
    List : TStrings; 
begin 
    try 
    List:=TStringList.Create; 
    try 
    SplitGSMMessage(GSMMessage, List); 
    Writeln(List.Text); 
    finally 
    List.Free; 
    end; 

    except 
    on E: Exception do Writeln(E.ClassName, ': ', E.Message); 
    end; 
    Readln; 
end. 
+3

+1しかし、その代わりに、真do'私は '休憩の必要性を排除しFoundOffset = 0 'になるまで繰り返しを好むだろうが、'のインチ – NGLN

+0

@NGLN良い提案。コードが編集されました。 – RRUZ

+1

@ NGLNここでTrueは良いですが。つまり、テストを複製するのではなく、FoundOffsetを0回だけテストできます。私はオリジナルを好むだろう。 –

関連する問題