2012-08-06 48 views
0

所以這可能很難解釋,但我想做一個for ...:= 1到10做聲明,但我希望它是爲A到N做。這個excersise的主要目的是將數據加載到字符串網格中。所以讓我們把字母A,B,C,D,E加到單元格0,1 0,2 0,3 0,4 0,5 0,6 0,7一直到14。如果有人知道如何做到這一點,我會非常感激!循環和增加字符串網格中的單元格的字母值

回答

6

在這裏,你得到了它,但我不知道這是否是一個很好的方式如何學習編程(我的意思是問問題的請求,這樣你別人寫的代碼):

procedure TForm1.Button1Click(Sender: TObject); 
var 
    I: Integer; 
begin 
    StringGrid1.FixedCols := 1; 
    StringGrid1.ColCount := 15; 
    for I := 1 to 14 do 
    StringGrid1.Cells[I, 1] := Chr(Ord('A') + I - 1); 
end; 
1

如果您要同時填補了StringGrid控制一排,你可以做

procedure TForm1.Button1Click(Sender: TObject); 
var 
    i: Integer; 
begin 
    StringGrid1.FixedCols := 1; 
    StringGrid1.FixedRows := 1; 
    for i := 0 to Min(25, (StringGrid1.ColCount-1) * (StringGrid1.RowCount-1)) do 
    StringGrid1.Cells[i mod (StringGrid1.ColCount - 1) + 1, 
     i div (StringGrid1.ColCount - 1) + 1] := Chr(Ord('A') + i); 
end; 

這無論多少行和cols怎麼有工作的。

+1

@TLama:無需刪除您的帖子!你是第一個,也許馬特實際上只是想填補第一排。我們的答案是相輔相成的。另外,對於一個絕對的新手來說,雖然你的代碼可能是可理解的,但我的可能是非透明的(大量的+ -1,非常奇怪的'mod'操作符,更不用說隱藏的'Min'了在'Math'單元中)。 – 2012-08-06 10:02:51

+0

好的,你說服我撤消刪除:-)然而,馬特可以使用你的部分代碼,我想。看來['buttons'](http://stackoverflow.com/q/11806495/960757)畢竟不會被使用。 – TLama 2012-08-06 10:10:31

0

想融合TLama的回答與「希望做一個爲...:= 1〜10做的語句,但我想這是對於A至N做」

不知道它會是雙關,還是啓發。

var c: char; i: integer; 
    s: string; 
    ... 
    i := 0; s:= EmptyStr; 
    for c := 'A' to 'N' do begin 
     s := s + c + ','; 
     Inc(i); 
    end; 

    SetLength(s, Length(s) - 1); // we do not need last comma there 
    StringGrid1.ColCount := i; 
    StringGrid1.Rows[0].CommaText := s; 

或者使用TStringBuilder相同 - 這比在每個新的字符串修改上重新安排Heap更快。

uses SysUtils; 
    ... 
var c: char; i: integer; 
    s: string; 
    ... 
    i := 0; 
    with TStringBuilder.Create do try 
    for c := 'A' to 'N' do begin 
     Append(c + ','); 
     Inc(i); 
    end; 
    s := ToString; 
    finally 
    Free; 
    end; 

    SetLength(s, Length(s) - 1); // we do not need last comma there 
    StringGrid1.ColCount := i; 
    StringGrid1.Rows[0].CommaText := s; 
+0

嗯,我基本上想顯示使用char循環,因爲原來的問題聽起來像。你可以這樣做* .Cells [1 + ord(c)-ord('A'),1]:= c *。或者你可能有* char *數組作爲StringBuilder的替代品。但是這會妨礙清晰度。即使對像StringGrid這樣簡單的對象,我也不會更快,它可以單獨調用CommaText setter來進行內部解析,也可以使用內部結構或者使用循環調用來使用Cell setter。或許我看到很多* TDataSet.Fields ['some-stirng']:= any-var; * snippets而不是像TDataSet.AppendRecord :-) – 2012-08-06 15:59:21

+0

@TLama,你會重新激活你的評論或什麼嗎?我迷路了。 – 2012-08-06 15:59:47

+0

讓它成爲:-)我意識到你可以使用像A,B,C,D ...這樣的常量字符串來代替循環連接。這就是爲什麼我刪除了我的評論。 – TLama 2012-08-06 17:54:37

相關問題