2011-09-20 76 views
2

如何將一行文本(例如,Hello there*3)分割成一個數組? *之前的所有內容都需要添加到第一個元素,並且*之後的所有內容都需要添加到第二個元素。我相信這是可能的。我需要後來想起這與第一和第二項必須彼此相關如何在特定字符處分割字符串?

我用Delphi 7

+0

你的「一個例子線'看起來更像*三條線,對我來說。也許你應該澄清一下輸入和預期輸出是什麼。 –

+1

您使用的是哪個版本的delphi? – RRUZ

+1

你說的是'多維數組',但你的例子表明你只對一維數組感興趣...... –

回答

4
type 
    TStringPair = array[0..1] of string; 

function SplitStrAtAmpersand(const Str: string): TStringPair; 
var 
    p: integer; 
begin 
    p := Pos('&', Str); 
    if p = 0 then 
    p := MaxInt - 1;  
    result[0] := Copy(Str, 1, p - 1); 
    result[1] := Copy(Str, p + 1); 
end; 

或者,如果你不進入魔力,

function SplitStrAtAmpersand(const Str: string): TStringPair; 
var 
    p: integer; 
begin 
    p := Pos('&', Str); 
    if p > 0 then 
    begin 
    result[0] := Copy(Str, 1, p - 1); 
    result[1] := Copy(Str, p + 1); 
    end 
    else 
    begin 
    result[0] := Str; 
    result[1] := ''; 
    end; 
end; 

如果,對於一些完全陌生而略顯怪異的原因,需要一個過程,不是一個函數,然後做

procedure SplitStrAtAmpersand(const Str: string; out StringPair: TStringPair); 
var 
    p: integer; 
begin 
    p := Pos('&', Str); 
    if p > 0 then 
    begin 
    StringPair[0] := Copy(Str, 1, p - 1); 
    StringPair[1] := Copy(Str, p + 1); 
    end 
    else 
    begin 
    StringPair[0] := Str; 
    StringPair[1] := ''; 
    end; 
end; 
+0

@David:這就是爲什麼我只是在你發表評論之前就修復它的原因! –

+0

這真的很讓人傷心,特別是與你只需要一行代碼的Python極其便攜的解決方案相比:''你好* 3'.split('*')' –

+1

@David:我想我正在爲打高爾夫球... –