我希望将包含多条记录的字符串拆分为字符串列表中的各个项目。 (德尔福7。)
以下是单个长字符串中的原始文本:
+ CMGL:0,“REC UNREAD”,“+ 27832729407”,,“12/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个字符总是正常,是我的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是新行的开头)
我可以从这里开始使用它,因为它是统一的。我将不胜感激任何帮助。我希望这是有道理的。
谢谢!
答案 0 :(得分: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.