文章摘要
这篇文章介绍了Lua编程语言中`string.len()`函数的使用方法及其核心功能。该函数用于计算字符串的长度,并特别指出,即使字符串包含` `字符,也会被计入长度统计。文章通过具体的代码示例展示了如何调用该函数,包括常规字符串、包含` `的字符串以及不同写法的使用方法。此外,文章还强调了该函数与C语言中类似功能的不同之处,并提醒读者注意这一点。总结来看,`string.len()`函数在处理字符串时非常强大且灵活,适用于多种场景。
前言
今天是星期天,我还是不浪费大家的脑细胞了,直接来列举一个string家族中比较简单的函数,函数虽然简单,但是用处却很大,使用频率也很高,废话不多说,我们直接来看函数用法。
内容
string.len()
原型:string.len(s)
解释:返回所给字符串的长度,如果字符串中包含’\0’,也会被统计为一个字符。
Usage
首先新建一个文件将文件命名为lentest.lua然后编写如下代码:
— 一个常规字符串
local sourcestr=”This is a rainy day!”
local sourcelen=string.len(sourcestr)
print(“\nthe len of sourcestr is “..sourcelen)
local sourcelen=string.len(sourcestr)
print(“\nthe len of sourcestr is “..sourcelen)
— 包含’\0’的字符串
local str=”Hello Lua \000 What?”
local strlen=string.len(str)
print(“\nthe len of str is “..strlen)
local strlen=string.len(str)
print(“\nthe len of str is “..strlen)
— 换一种写法
local strlen_new=str:len()
print(“\nthe len of str is “..strlen_new)
print(“\nthe len of str is “..strlen_new)
运行结果

总结
这个函数也会统计字符串中’\0’的个数,这和c语言是不一样的,这一点需要注意
第三组测试我是为了复习一下string家族中所有函数的另一种写法,其实以前也总结过,只不过今天在这里再次巩固一下
您可能感兴趣的文章:Lua中的string库和强大的模式匹配学习笔记Lua loadstring函数用法实例Lua中的loadfile、dofile、loadstring、require用法实例Lua字符串库(string库)学习笔记LUA string库使用小结Lua中的string库(字符串函数库)总结Lua中实现StringBuffer功能Lua中字符串(string)浅析Lua中string.lower()使用指南
© 版权声明
文章版权归作者所有,未经允许请勿转载。



