04 複製字串

你可能想給一個字符串變量複製到另一個。有一個特殊的詞,命名“CMOVE”。 

它以兩個字符串並複製字符的給定數目從源到目的地。讓我們 

看看這個例子:

: place over over >r >r char+ swap chars cmove r> r> c! ;

create one 16 chars allot \ define the first string

create two 16 chars allot \ define the second string

s" Greetings!" one place \ initialize string one

one dup \ save the real address

count \ get the length of string one

1+ \ account for the count byte

swap drop \ get the real address

two swap \ get the order right

cmove \ copy the string

two count type cr \ print string two

最困難的部分,了解可能是為什麼,以及如何建立數據“CMOVE”。

好吧,“CMOVE”希望看到在堆棧中的值: source destination #chars

用表達:

one count

我們得到的堆棧這些數據:source+1 length

但數字節尚未占到至今。 

 這就是為什麼我們地址:

1+

所以,現在這個參數的正確值。 

現在我們要恢復的字符串的地址,而且告訴“CMOVE”在哪裡串1的內容複製到。 

最初,我們得到了正確的地址。 

這就是為什麼我們救了它使用:Dup

現在,我們擺脫了“損壞”的地址發出:swap drop

這就是我們得到了現在:source #chars

如果我們簡單地添加:two

該數據還沒有出現在正確的順序:source #chars destination

所以,我們為了得到它的權利添加額外的“交換”。 

當然,你可以定義一個詞,照顧所有的:

: place over over >r >r char+ swap chars cmove r> r> c! ;

: copy$ swap dup count 1+ swap drop rot swap cmove ;

create one 32 chars allot

create two 32 chars allot

s" Greetings!" one place

one two copy$