|
| 1 | +package pl.mperor.lab.java.data.type; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Assertions; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.Locale; |
| 8 | + |
| 9 | +public class StringTest { |
| 10 | + |
| 11 | + @Test |
| 12 | + public void testStringCommonlyUsedMethods() { |
| 13 | + String abc = "abc"; |
| 14 | + Assertions.assertEquals(3, abc.length()); |
| 15 | + Assertions.assertTrue(abc.contains("b")); |
| 16 | + Assertions.assertTrue(!abc.isBlank() && !abc.isEmpty()); |
| 17 | + Assertions.assertTrue(abc.startsWith("a") && abc.endsWith("c")); |
| 18 | + Assertions.assertEquals("a*c", abc.replace('b', '*')); |
| 19 | + Assertions.assertEquals("bc", abc.substring(1, abc.length())); |
| 20 | + Assertions.assertArrayEquals(new String[]{"google", "com"}, "google.com".split("\\.")); |
| 21 | + Assertions.assertTrue("-1".matches("^-?\\d+$"), "Like isInteger(...)"); |
| 22 | + } |
| 23 | + |
| 24 | + @Test |
| 25 | + public void testStringImmutability() { |
| 26 | + String original = "| Fix"; |
| 27 | + String modified = original |
| 28 | + .replace('|', ' ') |
| 29 | + .strip() |
| 30 | + .concat("ed") |
| 31 | + .toUpperCase(); |
| 32 | + |
| 33 | + Assertions.assertEquals("| Fix", original); |
| 34 | + Assertions.assertEquals("FIXED", modified); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void testCompareStrings() { |
| 39 | + String qwerty = "qwerty"; |
| 40 | + String newQwerty = new String(qwerty); |
| 41 | + Assertions.assertTrue("qwerty" == qwerty, "String Pool exits!"); |
| 42 | + Assertions.assertFalse(qwerty == newQwerty); |
| 43 | + Assertions.assertTrue(qwerty == newQwerty.intern(), "'intern()' returns string from the pool"); |
| 44 | + Assertions.assertTrue(qwerty.equals(newQwerty)); |
| 45 | + Assertions.assertTrue(qwerty.equalsIgnoreCase("Qwerty")); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void testEscapeSequences() { |
| 50 | + String doubleQuote = "\"Title\""; |
| 51 | + String tabulator = "\tabc"; |
| 52 | + String backslash = "C:\\Windows"; |
| 53 | + String newLine = "...\n***"; |
| 54 | + String carriageReturn = "[ ] 0%\r[==========] 100%"; |
| 55 | + String unicodeCode = "Copyright \u00A9"; |
| 56 | + List.of(doubleQuote, tabulator, backslash, newLine, carriageReturn, unicodeCode) |
| 57 | + .forEach(System.out::println); |
| 58 | + } |
| 59 | + |
| 60 | + @Test |
| 61 | + public void testStringFormatting() { |
| 62 | + // Format specifier: %[flags][width][.precision]conversion |
| 63 | + // Escaping %% |
| 64 | + String format = "%s | %d | %#x | %.2f | %b | %c | %% |%n"; |
| 65 | + String formatted = String.format(Locale.UK, format, "Str", 1, 10, 1.23, true, '.'); |
| 66 | + var separator = System.getProperty("line.separator"); |
| 67 | + Assertions.assertEquals("Str | 1 | 0xa | 1.23 | true | . | % |" + separator, formatted); |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments