2012-03-17 40 views
0

我期待分裂一個字符串包含多個記錄到字串列表中的單個項目。 (DELPHI 7.)德爾福分割一個字符串包含幾個記錄與各種分隔符

以下是在一個長字符串的原始文本:

+ CMGL:0, 「REC UNREAD」, 「+ 27832729407」 ,,「10/03/17,21 :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條消息中的文字OK

我從GSM設備收到它。最終字符2個字符總是OK,是我的GSM設備的結果。

這是我需要的結果是:

+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

您可以使用PosExCopy函數構建一個函數來拆分字符串。

檢查該樣本

{$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 2012-03-17 23:24:49

+0

@NGLN好建議。代碼編輯。 – RRUZ 2012-03-18 00:12:42

+1

@NGLN,而True在這裏很好。這意味着您可以只測試一次FoundOffset,而不是重複測試。我更喜歡原創。 – 2012-03-18 08:33:42