就是一个感觉像是 String Class 中的一个重载,方便了连接字符串与字符串、字符串与其他对象
String.format() behave like sprintf in C.
String all = String.join(" / ", "S", "M", "L", "XL");// all is the string "S / M / L / XL"String repeated = "Java".repeat(3); // repeated is "JavaJavaJava"
Code Units. In Java, the char type describes a code unit in the UTF-16 encoding. The supplemetary characters may require several code units.
Code Points. Is a code value that is associated with a character in an encoding scheme. the Unicode
String greeting = "你好👋";// the length of code units & true lengthint cuCount = greeting.length(); // is 4 int cpCount = greeting.codePointCount(0, greeting.length()); // is 3// get the code unit at argu positionchar first = greeting.charAt(0); // first is '你'char second = greeting.charAt(1); // second is '好'// get the code pointint index = greeting.offsetByCodePoints(0, 2); // this statement is for counting by code pointint cp = greeting.codePointAt(index); // the index is base on code unit
When Traverses a String
可以
int cp = sentence.codePointAt(i);if (Character.isSupplementaryCodePoint(cp)) i += 2; else i++;i--;if (Character.isSurrogate(sentence.charAt(i))) i--;int cp = sentence.codePointAt(i);
但明显感觉 quite painful,不如:
int[] codePoints = str.codePoints().toArray();String str = new String(codePoints, 0, codePoints.length-0);
转成数组处理更方便,因为每一个元素都是一个 code point
前面的 methods 中,codePointAt 虽然可以返回一个 code point,但是 index 还是基于 code unit 的,所以 此路不通
StringBuilder Class
Java string is immuable, so if we do need to build up strings from small pieces, use StringBuilder.
StringBuilder builder = new StringBuilder(); // build emptybuilder.append(ch); // appends a single character builder.append(str); // appends a stringString completedString = builder.toString(); // to String