跳到主要内容

String 字符串类

String 是 Alia 的内置字符串类,用于表示和处理文本数据。

创建字符串​

字面量​

const str1 = 'Hello World'
const str2 = "Hello World"

构造函数​

const str3 = new String 'Hello World'
const str4 = String 'Hello World'

实例方法​

length​

获取字符串的长度。

const str = 'Hello World'
print str.length ~ 输出 11

split​

将字符串分割成数组。分割支持 limit 限制项数。

const str = 'a,b,c,d'
const arr = str.split ','
print arr ~ 输出 ['a', 'b', 'c', 'd']
const arr2 = str.split ',' limit 2
print arr2 ~ 输出 ['a', 'b']

replace​

替换字符串中的所有匹配项。

const str = 'Hello World'
const newStr = str.replace 'World' with 'Alia'
print newStr ~ 输出 'Hello Alia'

slice​

提取字符串的一部分。

const str = 'Hello World'
print str.slice 0 to 5 ~ 输出 'Hello'
print str.slice 6 ~ 输出 'World'

includes​

检查字符串是否包含指定的子字符串。

const str = 'Hello World'
print str.includes 'World' ~ 输出 true
print str.includes 'Alia' ~ 输出 false

indexOf​

返回子字符串第一次出现的位置。

const str = 'Hello World'
print str.indexOf 'o' ~ 输出 4
print str.indexOf 'World' ~ 输出 6

trim​

去除字符串两端的空白字符。

const str = ' Hello World '
print str.trim ~ 输出 'Hello World'

toUpperCase​

该方法返回全大写形式的字符串。

const str = 'Hello World'
print str.toUpperCase ~ 输出 'HELLO WORLD'

toLowerCase​

该方法返回全小写形式的字符串。

const str = 'Hello World'
print str.toLowerCase ~ 输出 'hello world'

toNumber​

该方法返回字符串对应的数值。

const str = '42'
print str.toNumber ~ 输出 42

toBoolean​

空字符串与 '0' 对应 false,其余字符串对应 true。

const str = 'Hello'
print str.toBoolean ~ 输出 true
const empty = ''
print empty.toBoolean ~ 输出 false

toArray​

该方法返回由单个字符构成的数组。

const str = 'Hi'
print str.toArray ~ 输出 ['H', 'i']

toString​

返回字符串本身。

const str = new String 'Hello'
print str.toString ~ 输出 'Hello'

valueOf​

返回字符串的原始值。

const str = new String 'Hello'
print str.valueOf ~ 输出 'Hello'

字符串连接​

字符串连接通过 .. 运算符实现。

const str1 = 'Hello'
const str2 = 'World'
const result = str1 .. ' ' .. str2
print result ~ 输出 'Hello World'

示例代码​

const greeting = 'Hello, Alia!'
print greeting
print '字符串长度: ' .. greeting.length
const words = greeting.split ','
print '分割结果: ' .. words
const newGreeting = greeting.replace 'Alia' with 'World'
print '替换后: ' .. newGreeting
const part = greeting.slice 0 to 5
print '切片结果: ' .. part
if greeting.includes 'Alia' { print '字符串包含 "Alia"' }
const pos = greeting.indexOf 'Alia'
print '"Alia" 位置: ' .. pos
const padded = ' Hello '
print '去除空白: ' .. padded.trim

下一步​