将SysUtils.WrapText()与包含单引号的字符串一起使用

问题描述 投票:6回答:2

我正在尝试将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代码而不是单引号char,但问题仍然存在。此外,我检查了Lines.Count,它是1

image

我试过删除单引号字符:

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;

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

image

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

delphi escaping word-wrap delphi-2007
2个回答
5
投票

你描述的是故意行为。

在Delphi XE及更早版本中,WrapText() documentation包括以下声明:

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

在Delphi XE2之后,文档中省略了该语句,但仍然在RTL中实现了该行为。

我已经与Embarcadero开了一张关于这个遗漏的票:

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


1
投票

在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);
© www.soinside.com 2019 - 2024. All rights reserved.