超好用的字符串拼接类StringBuilder

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

字符串拼接类 StringBuilder

类似 Java 的 StringBuilder,拼接多个字符串。

  1. 支持空字符串过滤
  2. 支持多个字符串中间使用指定的字符拼接

StringBuilder.ets代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
* Copyright (c) 2024 @Dench.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export class StringBuilder {
private value: string[];

constructor() {
this.value = [];
}

append(str: string | number | undefined | null): StringBuilder {
this.value.push(String(str));
return this;
}

appendNotNull(str: string | number | undefined | null): StringBuilder {
if (str != null) {
this.value.push(String(str));
}
return this;
}

build(separator?: string): string {
return this.value.join(separator);
}
}

使用 Demo

1
2
3
4
5
6
7
8
let res = new StringBuilder()
.append("123")
.append("aaa")
.append("456")
.append("bbb")
.append("789")
.build(".");
console.info(res);
作者

Dench

发布于

2024-05-15

更新于

2024-05-15

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×