我有一个数据库列,它只能包含 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/