gpt4 book ai didi

delphi - 如何将字符串拆分为固定长度的子字符串数组?

转载 作者:行者123 更新时间:2023-12-03 18:35:12 30 4
gpt4 key购买 nike

我尝试制作一个具有很多字符的字符串,

var
a: String;
b: array [0 .. (section)] of String;
c: Integer;
begin
a:= ('some many ... text of strings');
c:= Length(a);
(some of code)


并使其每10个字符成数组。最后是字符串的剩余部分。

b[1]:= has 10 characters
b[2]:= has 10 characters
....
b[..]:= has (remnant) characters // remnant < 10


问候,

最佳答案

使用动态数组,并根据字符串的长度计算运行时所需的元素数。这是一个简单的例子:

program Project1;

{$APPTYPE CONSOLE}

uses
System.SysUtils;

var
Str: String;
Arr: array of String;
NumElem, i: Integer;
Len: Integer;
begin
Str := 'This is a long string we will put into an array.';
Len := Length(Str);

// Calculate how many full elements we need
NumElem := Len div 10;
// Handle the leftover content at the end
if Len mod 10 <> 0 then
Inc(NumElem);
SetLength(Arr, NumElem);

// Extract the characters from the string, 10 at a time, and
// put into the array. We have to calculate the starting point
// for the copy in the loop (the i * 10 + 1).
for i := 0 to High(Arr) do
Arr[i] := Copy(Str, i * 10 + 1, 10);

// For this demo code, just print the array contents out on the
// screen to make sure it works.
for i := 0 to High(Arr) do
WriteLn(Arr[i]);
ReadLn;
end.


这是上面代码的输出:

This is a
long strin
g we will
put into a
n array.

关于delphi - 如何将字符串拆分为固定长度的子字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41093480/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com