2016-12-12 6 views
1
私は多くの文字を持つ文字列を作成しようとする

文字列を固定長部分文字列の配列に分割するにはどうすればよいですか?

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 

に関して、

+0

可能な重複//stackoverflow.com/questions/31943087/fast-way-to-split-a-string-into-fixed-length-parts-in-delphi) –

答えて

2

は、動的配列を使用して、あなたは、文字列の長さに基づいて、実行時に必要な要素の数を計算します。ここではそれを行うための簡単な例です:

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. 

ここでは上記のコードの出力です::[Delphiで固定長部分に文字列を分割するための高速な方法](HTTPの

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

FWIW、 'NumElem:= Len div 10;もしLen mod 10 <> 0ならInc(NumElem); 'NumElem:=(Len + 9)div 10;'を使うことができます。 –

関連する問題