Java - String

> Procedural Languages > Java

1 - About

Advertising

3 - Management

3.1 - Initialization

3.1.1 - From a byte array

from a Java - Byte

new String(myByteArray, "UTF-8");

3.2 - 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

3.3 - 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(", "));

3.4 - Multiplication

  • 10 character A
final int generation = 10;
String multi = new String(new char[generation]).replace("\0", "A");
System.out.println(multi);
AAAAAAAAAA
Advertising

3.5 - File

With Java - (Nio|New I/O) Package

// Write
Files.write(path, query.getBytes());
// Read
new String(Files.readAllBytes(path));

3.6 - toCharacterStream

  • 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())

3.7 - toUpperCase

import static java.util.Locale.ENGLISH;
tableName = tableName.toUpperCase(ENGLISH);