Logo - 字串



任何字母數字字元序列,例如 - “america”、“emp1234”等,都是字串的示例。字元計數是所有字串程序中最基本的。問題stringlength "abc12ef 的答案由以下過程給出 -

to stringlength :s
   make "inputstring :s
   make "count 0
   while [not emptyp :s] [
      make "count :count + 1
      print first :s
      make "s butfirst :s
   ]
   print (sentence :inputstring "has :count "letters)
end

在上述過程中 -“s”是包含輸入字串的變數。變數 inputstring 包含輸入字串的副本。變數 count 初始化為 0。在 while 迴圈中,條件檢查字串是否已變為空。在每個迴圈計數中,變數會增加 1 以持有長度計數。語句print first :s,僅列印儲存在“s”中的字串的第一個字元。

語句make "s butfirst :s,檢索不包含第一個字元的子字串。退出 while 迴圈後,我們列印了字元計數或輸入字串的長度。以下是程式碼的執行和輸出。

Strings
廣告