Java Рядки

2075 / Java / Рядки

 

Форматування виводу

 

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("\\."); // розбити по '.'
String[] words = a.split("\\s+"); // розбити по " ", "  ", "   "
String[] lines = str.split("\\r?\\n"); // розбити по переносу рядка UNIX & Windows
 
Лише цифри
String numberOnly = str.replaceAll("\\D+", "");
 
Лише букви
String letterOnly = str.replaceAll("\\d+", "");

Більше
str.copyValueOf(charArr, 0, 5); // char -> string
str.compareToIgnoreCase(str2); // 0 - рівні, 1, -1, нечутливий до регістру
str.compareTo(str2); // 0 - рівні, 1, -1
str.contentEquals(str2); // true - рівні
str.endsWith("llo"); // закінчується на
str.format(); // форматує
str.getBytes(); // перетворює в масив байтів
str.getChars(); // string -> char
str.hashCode(); // 69609650
str.concat(str2); // об'єднує рядки
str.startsWith(); // починається з char
x.toString(); // конвертувати в рядок
String.valueOf(x); // конвертувати в рядок
 

Розбити з обмеженням
String str = "004-034556-42";
String[] parts = str.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42

Прибрати дублікати
String str = "aaabbbccc";
char[] chars = str.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());