Операції з рядками
String a = "Hello Bill Gates.";
a.length() // 17
a.replace('G', 'J') // Hello Bill Jates. (char, char)
a.replaceAll("Gates", "Jobs") // Hello Bill Jobs. (string, string)
a.toLowerCase() // hello bill gates.
a.toUpperCase() // HELLO BILL GATES.
a.contains("Bill") // true, містить підрядок
a.startsWith('H') // true, починається з рядка
a.equals("Hello Bill Gates.") // true, дорівнює рядку
a.equalsIgnoreCase()("Hello Bill Gates.") // true, ігнорує регістр
a.indexOf("Bill") // 6 -1 не знайшов
a.indexOf("Bill", 1) // 6 -шукати з 1-ї позиції
a.lastIndexOf("Bill") // 6 -1 не знайшов, шукає з кінця, позиція як з початку
a.substring(6, 10) // Bill позиція початкова і кінцева
" 12 ".trim(' ') // 12 прибрати пробіли до і після фрази
a.isEmpty() // false, чи рядок пустий
a.charAt(0) // H get, char-формат
Спеціальні символи: \\, \', \"
\n - нова лінія (\r)
\t - табуляція
\b - на один символ назад
String[] words = a.split(" "); // розбити по ' '
String[] words = a.split("\\s+"); // розбити по " ", " ", " "
String lines[] = string.split("\\r?\\n"); // розбити по переносу рядка UNIX & Windows
Лише цифри
String numberOnly = str.replaceAll("\\D+", "");
Лише букви
String letterOnly = str.replaceAll("\\d+", "");
str1.copyValueOf(charArr, 0, 5); // char -> string
str1.compareToIgnoreCase(str2); // 0 - рівні, 1, -1, нечутливий до регістру
str1.compareTo(str2); // 0 - рівні, 1, -1
str1.contentEquals(str2); // true - рівні
str1.endsWith("llo"); // закінчується на
str1.format(); // форматує
str1.getBytes(); // перетворює в масив байтів
str1.getChars(); // string -> char
str1.hashCode(); // 69609650
str1.concat(str2); // об'єднує рядки
str1.startsWith(); // починається з char
x.toString(); // конвертувати в рядок
String.valueOf(x); // конвертувати в рядок
розбити з обмеженням
String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
прибрати дублікати
String string = "aaabbbccc";
char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars)
{
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet)
{
sb.append(character);
}
System.out.println(sb.toString());