Appearance
StringJoiner
To concatenate strings efficiently, StringBuilder should be used.
Many times, the strings we concatenate look like this:
java
// output: Hello Bob, Alice, Grace!
public class Main {
public static void main(String[] args) {
String[] names = {"Bob", "Alice", "Grace"};
var sb = new StringBuilder();
sb.append("Hello ");
for (String name : names) {
sb.append(name).append(", ");
}
// Pay attention to remove the last", ":
sb.delete(sb.length() - 2, sb.length());
sb.append("!");
System.out.println(sb.toString());
}
}The need to join arrays with delimiters is very common, so the Java standard library also provides a StringJoiner to do this:
java
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
String[] names = {"Bob", "Alice", "Grace"};
var sj = new StringJoiner(", ");
for (String name : names) {
sj.add(name);
}
System.out.println(sj.toString());
}
}Wait! The result of using StringJoiner is that the front "Hello " and the ending "!" are missing! In this case, you need to specify the "beginning" and "end" for StringJoiner :
java
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
String[] names = {"Bob", "Alice", "Grace"};
var sj = new StringJoiner(", ", "Hello ", "!");
for (String name : names) {
sj.add(name);
}
System.out.println(sj.toString());
}
}String.join()
String also provides a static method join() , which uses StringJoiner internally to splice strings. When there is no need to specify the "beginning" and "end", it is more convenient to use String.join() :
java
String[] names = {"Bob", "Alice", "Grace"};
var s = String.join(", ", names);Practise
Please use StringJoiner to construct a SELECT statement:
java
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
String[] fields = { "name", "position", "salary" };
String table = "employee";
String select = buildSelectSql(table, fields);
System.out.println(select);
System.out.println("SELECT name, position, salary FROM employee".equals(select) ? "测试成功" : "测试失败");
}
static String buildSelectSql(String table, String[] fields) {
// TODO:
return "";
}
}Summary
When splicing string arrays with specified delimiters, it is more convenient to use StringJoiner or String.join() ;
When using StringJoiner to join strings, you can also append an additional "beginning" and "end".