Delphi:即使设置了分隔符,字符串列表分隔符也始终是空格字符 [英] Delphi: StringList Delimiter is always a space character even if Delimiter is set

查看:17
本文介绍了Delphi:即使设置了分隔符,字符串列表分隔符也始终是空格字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 TStringList 类中的分隔符时遇到问题.看一看:

I am having trouble with the delimiter in the TStringList Class. Take a look:

var
  s: string;
  sl: TStringList;

begin
  sl := TStringList.Create;
  s := 'Users^foo bar^bar foo^foobar^barfoo';
  sl.Delimiter := '^';
  sl.DelimitedText := s;
  ShowMessage(sl[1]);
end;

sl[1] 应该返回 'foo bar'

sl[1] 确实返回 'foo'

现在好像分隔符是 '^' AND ' '

It seems that the delimiter is now '^' AND ' '

有什么想法吗?

推荐答案

您应该将 s1.StrictDelimiter := True 设置为不被视为分隔符的空格,更多信息 这里.

You should set s1.StrictDelimiter := True for spaces not to be considered delimiters, more info here.

由于您使用的版本不支持上述(如提交答案后澄清),您有两个选择:

Since you work in a version that does not support the above (as was clarified after the answer was submitted), you have two options:

  1. 找到一个你知道不会在原始文本中使用的字符(例如下划线),在拆分前将所有空格转换为该字符,并在拆分后转换回来.这是robosoft的建议.
  2. 如果文本中没有引号和空格,则可以使用 Alexander 的技巧和换行反转命令中分隔符之间的文本,以便 'hello hello^bye bye' 变成 '"hello hello"^"bye bye"'.如果您确实选择了这条路径并且它适合您,请接受亚历山大的回答而不是我的,他还提供了实现它的代码.
  1. Find a character you know will not be used in the original text (e.g. underscore), convert all spaces to that character before splitting, and convert back after splitting. This is robosoft's suggestion.
  2. If you don't have inverted commas and spaces in the text, you can use Alexander's trick and wrap the text between delimiters in inverted command, so that 'hello hello^bye bye' turns to '"hello hello"^"bye bye"'. If you do choose this path and it works for you, please accept Alexander's answer and not mine, he also provides the code to implement it.

不使用 StrictDelimiter 的两种解决方法都有局限性:第一个需要一些未使用的字符,第二个不需要原始文本中的引号和空格.

Both workarounds not using StrictDelimiter have limitations: the first requires some unused character, and the second requires no inverted commas and spaces in the original text.

也许是时候升级到更新版本的 Delphi 了 :)

Maybe it's time to upgrade to a newer version of Delphi :)

这篇关于Delphi:即使设置了分隔符,字符串列表分隔符也始终是空格字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆