2016-12-12 4 views
1

i essayer de faire une chaîne qui a beaucoup de caractère,Comment diviser une chaîne en un tableau de sous-chaînes de longueur fixe?

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

et le rendre dans un tableau par 10 caractères. au dernier est le reste de la ficelle.

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

salutations,

+0

double possible de [Manière rapide de diviser une chaîne en plusieurs parties de longueur fixe dans Delphi] (http: //stackoverflow.com/questions/31943087/fast-way-to-split-a-string-into-fixed-length-parts-in-delphi) –

Répondre

2

Utilisez un tableau dynamique, et de calculer le nombre d'éléments dont vous avez besoin lors de l'exécution en fonction de la longueur de la chaîne. Voici un exemple rapide de le faire:

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. 

Voici la sortie du code ci-dessus:

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

FWIW, au lieu de 'NumElem: = Len div 10; si Len mod 10 <> 0 alors Inc (NumElem); 'vous pouvez faire' NumElem: = (Len + 9) div 10; ', ce qui est un peu plus court. –