如何遍历定界字符串并将字符串内容分配给本地delphi变量? [英] How can I loop through a delimited string and assign the contents of the string to local delphi variables?
问题描述
我编写了一个Delphi函数,该函数将.dat文件中的数据加载到字符串列表中.然后,它解码字符串列表并分配给字符串变量.字符串的内容使用'#'符号作为分隔符.
I have written a Delphi function that loads data from a .dat file into a string list. It then decodes the string list and assigns to a string variable. The contents of the string use the '#' symbol as a separator.
然后如何获取此字符串的内容,然后将其内容分配给局部变量?
How can I then take the contents of this string and then assign its contents to local variables?
// Function loads data from a dat file and assigns to a String List.
function TfrmMain.LoadFromFile;
var
index, Count : integer;
profileFile, DecodedString : string;
begin
// Open a file and assign to a local variable.
OpenDialog1.Execute;
profileFile := OpenDialog1.FileName;
if profileFile = '' then
exit;
profileList := TStringList.Create;
profileList.LoadFromFile(profileFile);
for index := 0 to profileList.Count - 1 do
begin
Line := '';
Line := profileList[Index];
end;
end;
在解码后,变量"Line"包含如下内容:
After its been decoded the var "Line" contains something that looks like this:
示例:
Line '23#80#10#2#1#...255#'.
并非所有分隔符之间的值都具有相同的长度,并且每次调用LoadFromFile函数时,"Line"的值都会变化(例如,有时一个值可能只有一个数字,接下来的两个或三个数字等等,所以我不能依赖于复制函数来获取字符串或数组.
Not all of the values between the separators are the same length and the value of "Line" will vary each time the function LoadFromFile is called (e.g. sometimes a value may have only one number the next two or three etc so I cannot rely on the Copy function for strings or arrays).
我试图找出一种循环浏览行"内容的方法,将其分配给一个名为缓冲区"的局部变量,然后如果遇到#",则将缓冲区的值分配给一个局部变量,将缓冲区重新初始化为'';然后移至行"中的下一个值,并重复执行下一个参数的过程,每次都忽略#".
I'm trying to figure out a way of looping through the contents of "Line", assigning it to a local variable called "buffer" and then if it encounters a '#' it then assigns the value of buffer to a local variable, re-initialises buffer to ''; and then moves onto the next value in "Line" repeating the process for the next parameter ignoring the '#' each time.
我认为我已经很久没有解决这个问题了,我似乎无法取得任何进展,需要有所突破.如果有人愿意看一看,我将欢迎您提出任何有关如何实现此目标的建议.
I think I have been scratching around with this problem for too long now and I cannot seem to make any progress and need a break from it. If anyone would care to have a look, I would welcome any suggestions on how this might be achieved.
非常感谢
KD
推荐答案
您需要第二个TStringList:
You need a second TStringList:
lineLst := TStringList.Create;
try
lineLst.Delimiter := '#';
lineLst.DelimitedText := Line;
...
finally
lineLst.Free;
end;
如果行中包含空格,则可以设置lineLst.StrictDelimiter := true
,具体取决于您的Delphi版本.
Depending on your Delphi version you can set lineLst.StrictDelimiter := true
in case the line contains spaces.
这篇关于如何遍历定界字符串并将字符串内容分配给本地delphi变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!