About
Text - String in Java.
Management
Initialization
From a byte array
from a Java - Byte
new String(myByteArray, "UTF-8");
From a array of characters
Arrays.toString("Hello, World!".toCharArray())
From a collection of character
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(charactersList);
return stringBuilder.toString();
Construction of large String
- A StringWriter is A character stream that collects its output in a string buffer, which can then be used to construct a string.
- StringBuilder
Join
- The string join method on array
String str = String.join(",", arr);
- or with a stream and the Collectors.joining function
// Example a list of column names join with a comma delimiter
String columnStatement = IntStream.range(0,source.getDataDef().getColumnDefs().size())
.mapToObj(i->source.getDataDef().getColumnDef(i).getColumnName())
.collect(Collectors.joining(", "));
Multiplication
- 10 character A
final int generation = 10;
String multi = new String(new char[generation]).replace("\0", "A");
System.out.println(multi);
AAAAAAAAAA
File
With Java - (Nio|New I/O) Package
// Write
Files.write(path, query.getBytes());
// Read
new String(Files.readAllBytes(path));
toCharacter
- Stream: Example when calculating the number of digits
// THe trick is that s.chars() returns characters as int
Math.toIntExact(s.chars()
.filter(i->Character.isDigit((char) i)))
.count())
- For
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
toUpperCase
import static java.util.Locale.ENGLISH;
tableName = tableName.toUpperCase(ENGLISH);
Replace with regexp pattern
- How to replace a string with a pattern object.
Pattern pattern = Pattern.compile("pattern");
String replaced = pattern.matcher(text).replaceFirst("");