在 Squirrel 语言中,endswith
是字符串函数,用于判断当前字符串是否以指定的子字符串结尾,返回布尔值(true
或 false
)。
基本语法
squirrel
endswith(string,suffix)
- 参数:string 为当前字符串
suffix
是要检查的子字符串。 - 返回值:如果原字符串以
suffix
结尾,返回true
;否则返回false
。
示例用法
squirrel
local str = "Hello, world!";
// 检查字符串是否以 "world!" 结尾
print(endswith(str,"world!")); // 输出: true
// 检查字符串是否以 "Hello" 结尾
print(endswith(str,"Hello")); // 输出: false
// 检查空字符串(任何字符串都以空字符串结尾)
print(endswith(str,"")); // 输出: true
// 区分大小写
local str2 = "Test.txt";
print(endswith(str2,".TXT")); // 输出: false(大小写不匹配)
注意事项
- 大小写敏感:
endswith
区分字母大小写,例如.txt
和.TXT
会被视为不同的后缀。 - 空字符串:任何字符串都默认以空字符串
""
结尾,因此调用endswith(str,"")
始终返回true
。 - 参数类型:
suffix
必须是字符串类型,若传入其他类型(如数字),可能会导致运行时错误。
通过 endswith
方法,可以方便地实现文件后缀判断(如判断是否为 .txt
文件)、字符串结尾匹配等场景。