【问题标题】:Using SysUtils.WrapText() with strings containing single quotes将 SysUtils.WrapText() 与包含单引号的字符串一起使用
【发布时间】:2019-03-29 17:38:51
【问题描述】:

我正在尝试将 SysUtils.WrapText() 函数与包含转义单引号字符的字符串一起使用,但我得到了意想不到的结果。

var
  Lines : TStrings;
begin
  Lines := TStringList.Create;
  try
    Lines.Text := WrapText('Can''t format message, message file not found', 15);
    ShowMessage(Lines.Text);
  finally
    Lines.Free;
  end;
end;

如果字符串包含撇号字符,该函数似乎根本不包装字符串。

我也尝试使用#39 代码而不是单引号字符,但问题仍然存在。此外,我检查了Lines.Count,它是1

我已经尝试删除单引号字符:

var
  Lines : TStrings;
begin
  Lines := TStringList.Create;
  try
    Lines.Text := WrapText('Cant format message, message file not found', 15);
    ShowMessage(Lines.Text);
  finally
    Lines.Free;
  end;
end;

它开始按预期包装字符串:

我想知道为什么会发生这种情况,我应该如何使用带有此类字符串的 WrapText() 函数?

【问题讨论】:

  • 看起来它不会分解/忽略引号之间的文本。添加另一个引号,它开始拆分文本。
  • 你试过Lines.Text := WrapText('Cant format message, message file not found', [' '], 15);吗?
  • @Sam:这改变了文本的含义。 Can'tcan not 的缩写,而 cant 是倾斜或斜面的表面。 :-)

标签: delphi escaping word-wrap delphi-2007


【解决方案1】:

你描述的是故意行为

在 Delphi XE 及更早版本中,WrapText() documentation 包含以下语句:

WrapText 不会在嵌入的带引号的字符串中插入分隔符(支持单引号和双引号)。

在 Delphi XE2 及以后的版本中,文档中省略了该语句,但该行为仍在 RTL 中实现。

我已向 Embarcadero 开出一张关于此遗漏的票:

RSP-24114: Important clause about embedded quoted strings is missing from WrapText documentation

【讨论】:

  • 感谢您的解释,所以它会看到单引号后面的部分,就像它是嵌入的带引号的字符串一样......你知道WrapText的任何替代函数吗?
  • @Fabrizio 我没有。您可能必须自己动手,或找到不跳过嵌入式引号字符串的第 3 方实现。
【解决方案2】:

在 10.3.1 中,源代码包含处理引号字符的代码,包括双引号和单引号,看起来只是忽略它们之间的文本。因此,一种解决方案是使用与单引号字符不同的撇号。第二个是避免使用收缩。函数源码的开始:

function WrapText(const Line, BreakStr: string; const BreakChars: TSysCharSet;
  MaxCol: Integer): string;
const
  QuoteChars = ['''', '"'];
  FirstIndex = Low(string);
  StrAdjust = 1 - Low(string);
var
...

一个选项:

    Lines.Text := WrapText('Can`t format message, message file not found', 15);

第二种选择:

    Lines.Text := WrapText('Cannot format message, message file not found', 15);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多