[英]How to convert a string into array in delphi?
在php和java中,有explode和tokenizer函數,可將字符串轉換為沒有標點的數組。 是delphi中的函數或某種方式來完成工作。 假設有一個大文件“這是一個帶有標點符號,空格和數字123的大文件...”我們如何獲得數組“這是一個有標點符號,空格和數字123的大文件”
提前非常感謝您。
是的,我們只需要[0..9],[a..z],[A..Z],例如正則表達式中的\\ w。 我們可以在Tperlregex中使用regex提取\\ w並將它們放在Tstringlist中,就像tstringlist是一個數組一樣,但是效率可能不高嗎? 謝謝。
如果您需要一個接受字符串並返回字符串數組的函數,這些字符串是原始字符的子字符串,這些字符串以標點符號分隔,就像我以前的回答中Eugene所建議的那樣,那么您可以
type
StringArray = array of string;
IntegerArray = array of integer;
TCharSet = set of char;
function split(const str: string; const delims: TCharSet): StringArray;
var
SepPos: IntegerArray;
i: Integer;
begin
SetLength(SepPos, 1);
SepPos[0] := 0;
for i := 1 to length(str) do
if str[i] in delims then
begin
SetLength(SepPos, length(SepPos) + 1);
SepPos[high(SepPos)] := i;
end;
SetLength(SepPos, length(SepPos) + 1);
SepPos[high(SepPos)] := length(str) + 1;
SetLength(result, high(SepPos));
for i := 0 to high(SepPos) - 1 do
result[i] := Trim(Copy(str, SepPos[i] + 1, SepPos[i+1] - SepPos[i] - 1));
end;
例:
const
PUNCT = ['.', ',', ':', ';', '-', '!', '?'];
procedure TForm4.FormCreate(Sender: TObject);
var
str: string;
begin
for str in split('this, is, a! test!', PUNCT) do
ListBox1.Items.Add(str)
end;
這取決於“字母數字字符”和“剪裁字符”的定義。
例如,如果我們定義標點符號集
const
PUNCT = ['.', ',', ':', ';', '-', '!', '?'];
並考慮所有其他字符的字母數字,那么您可以
function RemovePunctuation(const Str: string): string;
var
ActualLength: integer;
i: Integer;
const
PUNCT = ['.', ',', ':', ';', '-', '!', '?'];
begin
SetLength(result, length(Str));
ActualLength := 0;
for i := 1 to length(Str) do
if not (Str[i] in PUNCT) then
begin
inc(ActualLength);
result[ActualLength] := Str[i];
end;
SetLength(result, ActualLength);
end;
此函數將字符串轉換為字符串。 如果您想將字符串轉換為字符數組,只需執行
type
CharArray = array of char;
function RemovePunctuation(const Str: string): CharArray;
var
ActualLength: integer;
i: Integer;
const
PUNCT = ['.', ',', ':', ';', '-', '!', '?'];
begin
SetLength(result, length(Str));
ActualLength := 0;
for i := 1 to length(Str) do
if not (Str[i] in PUNCT) then
begin
result[ActualLength] := Str[i];
inc(ActualLength);
end;
SetLength(result, ActualLength);
end;
(是的,在Delphi中,字符串使用基於1的索引,而數組使用基於0的索引。這是出於歷史原因。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.