codecamp

Logo 字符串

任何字母数字字符序列,例如americaemp1234等,都是字符串的示例。计算字符数是所有字符串过程中最基本的。问题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包含输入字符串的副本。变量计数初始化为 0。在 while 循环中,条件检查字符串是否为空。在每个循环计数中,一个变量增加 1 以保持长度计数。语句print first :s仅打印存储在s中的字符串的第一个字符。

语句make "s butfirst :s,检索不包括第一个字符的子字符串。退出while循环后,我们打印了输入字符串的字符数或长度。以下是代码的执行和输出.

Logo 决策
Logo 颜色
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定