delphi - delphi中如何将字符串剪切为所需的数字?

标签 delphi delphi-xe2 delphi-7

我有一个数据库列,它只能包含 40 个字符的字符串。因此,当字符串的长度大于 40 个字符时,就会出现错误。如何在delphi中将字符串剪切/修剪为40个字符?

最佳答案

var
  s: string;
begin
  s := 'This is a string containing a lot of characters.'
  s := Copy(s, 1, 40);
  // Now s is 'This is a string containing a lot of cha'

更奇特的是,如果字符串被截断,则添加省略号,以更清楚地表明这一点:

function StrMaxLen(const S: string; MaxLen: integer): string;
var
  i: Integer;
begin
  result := S;
  if Length(result) <= MaxLen then Exit;
  SetLength(result, MaxLen);
  for i := MaxLen downto MaxLen - 2 do
    result[i] := '.';
end;

var
  s: string;
begin
  s := 'This is a string containing a lot of characters.'
  s := StrMaxLen(S, 40)
  // Now s is 'This is a string containing a lot of ...'

或者,对于所有 Unicode 爱好者,您可以使用单个省略号字符保留两个以上的原始字符......(U+2026:水平省略号):

function StrMaxLen(const S: string; MaxLen: integer): string;
var
  i: Integer;
begin
  result := S;
  if Length(result) <= MaxLen then Exit;
  SetLength(result, MaxLen);
  result[MaxLen] := '…';
end;

var
  s: string;
begin
  s := 'This is a string containing a lot of characters.'
  s := StrMaxLen(S, 40)
  // Now s is 'This is a string containing a lot of ch…'

但是你必须确信你的所有用户及其亲属都支持这个不寻常的角色。

关于delphi - delphi中如何将字符串剪切为所需的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14936295/

相关文章:

performance - Delphi ADO 数据集过滤器

delphi - 泛型无法正确解析方法类型

delphi - JvTreeView 和 JvCheckTreeView 复选框通知

delphi - 透明TMemo-文本在未选中时似乎保持选中状态

delphi - Delphi7中如何增加MessageDlg宽度?

Delphi 7 类助手的先见之明

delphi - 是否有可用于 Delphi 的备用 XML 模式导入器?

delphi - 如何为特定控件创建自己的自定义提示?

delphi - 使用 DLL 和 WideString 时的竞争条件

德尔福XE2 : Off by 7-20 lines in debugger and compiler error line numbers also off by the same amount