1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 | package Torello.Java; import java.util.*; import java.util.regex.*; import java.util.zip.*; import java.io.*; import java.util.stream.*; import java.util.function.*; import java.text.DecimalFormat; import java.net.URL; import Torello.Java.Function.IntCharFunction; import Torello.Java.Function.IntTFunction; import Torello.Java.ReadOnly.ReadOnlyList; import Torello.Java.ReadOnly.ReadOnlyArrayList; import Torello.Java.Additional.Counter; /** * A plethora of extensions to Java's {@code String} class. * * <EMBED CLASS='external-html' DATA-FILE-ID=STRING_PARSE> */ @Torello.JavaDoc.StaticFunctional public class StringParse { private StringParse() { } // ******************************************************************************************** // ******************************************************************************************** // Constants // ******************************************************************************************** // ******************************************************************************************** private static final DecimalFormat formatter = new DecimalFormat("#,###"); /** * This regular expression simply matches white-space found in a java {@code String}. * @see #removeWhiteSpace(String) */ public static final Pattern WHITE_SPACE_REGEX = Pattern.compile("\\s+"); /** * This regular expression simply matches the comma. The only reason for including this here * is because the java {@code class 'Pattern'} contains a method called * {@code Stream<String> 'splitAsStream(CharSequence)'} which is used for the CSV method * further below * * @see StrCSV#CSV(String, boolean, boolean) * @see FileRW#readDoublesFromFile(String, boolean, boolean) * @see FileRW#readLongsFromFile(String, boolean, boolean, int) */ public static final Pattern COMMA_REGEX = Pattern.compile(","); /** * This regular expression is used for integer and floating-point numbers that use the * comma ({@code ','}) between the digits that comprise the number. For example, this * Regular Expression would match the {@code String} {@code "900,800,75.00"}. * * @see FileRW#readIntsFromFile(String, boolean, boolean, int) */ public static final Pattern NUMBER_COMMMA_REGEX = Pattern.compile("(\\d),(\\d)"); /** * This represents any version of the new-line character. Note that the {@code '\r\n'} version * comes before the single {@code '\r'} version in the regular-expression, to guarantee that * if both are present, they are treated as a single newline. */ public static final Pattern NEWLINEP = Pattern.compile("\\r\\n|\\r|\\n"); /** * Predicate for new-line characters * @see #NEWLINEP */ public static final Predicate<String> newLinePred = NEWLINEP.asPredicate(); /** The months of the year, as an immutable list of {@code String's}. */ public static final ReadOnlyList<String> months = new ReadOnlyArrayList<>( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ); private static final Calendar internalCalendar = Calendar.getInstance(); /** This is the list of characters that need to be escaped for a regular expression */ public static final String REG_EX_ESCAPE_CHARS = "\\/()[]{}$^+*?-."; /** Alpha-Numeric RegEx */ public static final Pattern ALPHA_NUMERIC = Pattern.compile("^[\\d\\w]*$"); /** * Alpha-Numeric {@code String} Predicate. * @see #ALPHA_NUMERIC */ public static final Predicate<String> alphaNumPred = ALPHA_NUMERIC.asPredicate(); // The minimum value for the byte primitive type, without the minus sign. private static final char[] BYTE_MIN_VALUE_DIGITS_AS_CHARS = { '2', '5', '6' }; // The minimum value for the short primitive type, without the minus sign. private static final char[] SHORT_MIN_VALUE_DIGITS_AS_CHARS = { '6', '5', '5', '3', '6' }; // The minimum value for the int primitive type, without the minus sign. private static final char[] INT_MIN_VALUE_DIGITS_AS_CHARS = { '2', '1', '4', '7', '4', '8', '3', '6', '4', '8' }; // The minimum value for the long primitive type, without the minus sign. private static final char[] LONG_MIN_VALUE_DIGITS_AS_CHARS = { '2', '1', '4', '9', '2', '2', '3', '3', '7', '2', '0', '3', '6', '8', '5', '4', '7', '7', '5', '8', '0', '8' }; /** An empty {@code String} array. */ public static final String[] EMPTY_STR_ARRAY = {}; // ******************************************************************************************** // ******************************************************************************************** // methods // ******************************************************************************************** // ******************************************************************************************** /** * Makes a {@code long} number like {@code 123456789} into a number-string such as: * {@code "123,456,789"}. Java's {@code package java.text.*} is easy to use, and versatile, but * the commands are not always so easy to remember. * * @param l Any {@code long} integer. Comma's will be inserted for every third power of ten * * @return After calling java's {@code java.text.DecimalFormat} class, a {@code String} * representing this parameter will be returned. */ public static String commas(long l) { return formatter.format(l); } /** * Trims any white-space {@code Characters} from the end of a {@code String}. * * <BR /><TABLE CLASS=JDBriefTable> * <TR><TH>Input String:</TH><TH>Output String:</TH></TR> * <TR><TD>{@code "A Quick Brown Fox\n \t"}</TD><TD>{@code "A Quick Brown Fox"}</TD></TR> * <TR><TD>{@code "\tA Lazy Dog."}</TD><TD>{@code "\tA Lazy Dog."}</TD></TR> * <TR><TD>{@code " " (only white-space)}</TD><TD>{@code ""}</TD></TR> * <TR><TD>{@code "" (empty-string)}</TD><TD>{@code ""}</TD></TR> * <TR><TD>{@code null}</TD><TD>throws {@code NullPointerException}</TD></TR> * </TABLE> * * @param s Any Java {@code String} * * @return A copy of the same {@code String} - <I>but all characters that matched Java * method {@code java.lang.Character.isWhitespace(char)}</I> and were at the end of the * {@code String} will not be included in the returned {@code String}. * * <BR /><BR />If the {@code zero-length String} is passed to parameter {@code 's'}, it * shall be returned immediately. * * <BR /><BR />If the resultant-{@code String} has zero-length, it is returned, without * exception. */ public static String trimRight(String s) { if (s.length() == 0) return s; int pos = s.length(); while ((pos > 0) && Character.isWhitespace(s.charAt(--pos))); if (pos == 0) if (Character.isWhitespace(s.charAt(0))) return ""; return s.substring(0, pos + 1); } /** * Trims any white-space {@code Characters} from the beginning of a {@code String}. * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input String:</TH><TH>Output String:</TH></TR> * <TR><TD>{@code "\t A Quick Brown Fox"}</TD><TD>{@code "A Quick Brown Fox"}</TD></TR> * <TR><TD>{@code "A Lazy Dog. \n\r\t"}</TD><TD>{@code "A Lazy Dog. \n\r\t"}</TD></TR> * <TR><TD>{@code " " (only white-space)}</TD><TD>{@code ""}</TD></TR> * <TR><TD>{@code "" (empty-string)}</TD><TD>{@code ""}</TD></TR> * <TR><TD>{@code null}</TD><TD>throws {@code NullPointerException}</TD></TR> * </TABLE> * * @param s Any Java {@code String} * * @return A copy of the same {@code String} - <I>but all characters that matched Java * method {@code java.lang.Character.isWhitespace(char)}</I> and were at the start of the * {@code String} will not be included in the returned {@code String}. * * <BR /><BR />If the {@code zero-length String} is passed to parameter {@code 's'}, it * shall be returned immediately. * * <BR /><BR />If the resultant-{@code String} has zero-length, it is returned, without * exception. */ public static String trimLeft(String s) { int pos = 0; int len = s.length(); if (len == 0) return s; while ((pos < len) && Character.isWhitespace(s.charAt(pos++))); if (pos == len) if (Character.isWhitespace(s.charAt(len-1))) return ""; return s.substring(pos - 1); } /** * Primarily for convenience in remembering earlier C-style {@code printf(...)} formatting * commands. * * <BR /><BR />This method will "left pad" an input {@code String} with spaces, if * {@code s.length() < totalStrLength}. If input-parameter {@code 's'} is equal-to or * longer-than the value in {@code 'totalStringLength'}, then the original {@code String} shall * be returned. * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input Parameters</TH><TH>Returned String</TH></TR> * <TR><TD>{@code "Quick Brown Fox"}<BR />{@code 20}</TD> * <TD><PRE>{@code " Quick Brown Fox"}</PRE></TD> * </TR> * <TR><TD>{@code "Hello World"}<BR />{@code 15}</TD> * <TD><PRE>{@code " Hello World"}</PRE></TD> * </TR> * <TR><TD>{@code "Write Once, Run Anywhere"}<BR />{@code 10}</TD> * <TD>{@code "Write Once, Run Anywhere"}</TD> * </TR> * <TR><TD>{@code null}</TD><TD>{@code NullPointerException}</TD></TR> * </TABLE> * * @param s This may be any {@code java.lang.String} * * @param totalStringLength If {@code s.length()} is smaller than {@code 'totalStringLength'}, * then as many space characters ({@code ' '}) as are needed to ensure that the returned * {@code 'String'} has length equal to {@code 'totalStringLength'} will be * <B><I>prepended</B></I> to the input {@code String} parameter {@code 's'}. * * <BR /><BR />If {@code s.length()} is greater than {@code 'totalStringLength'}, then the * original input shall be returned. * * @throws IllegalArgumentException If {@code totalStringLength} is zero or negative. * * @see #rightSpacePad(String, int) */ public static String leftSpacePad(String s, int totalStringLength) { if (totalStringLength <= 0) throw new IllegalArgumentException( "totalString length was '" + totalStringLength + ", " + "however it is expected to be a positive integer." ); return (s.length() >= totalStringLength) ? s : String.format("%1$" + totalStringLength + "s", s); } /** * Primarily for convenience in remembering earlier C-style {@code printf(...)} formatting * commands. * * <BR /><BR />This method will "right pad" an input {@code String} with spaces, if * {@code s.length() < totalStrLength}. If input-parameter {@code 's'} is equal-to or * longer-than the value in {@code 'totalStringLength'}, then the original {@code String} shall * be returned. * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input Parameters</TH><TH>Returned String</TH></TR> * <TR><TD>{@code "Quick Brown Fox"}<BR />{@code 20}</TD> * <TD><PRE>{@code "Quick Brown Fox "}</PRE></TD> * </TR> * <TR><TD>{@code "Hello World"}<BR />{@code 15}</TD> * <TD><PRE>{@code "Hello World "}</PRE></TD> * </TR> * <TR><TD>{@code "Write Once, Run Anywhere"}<BR />{@code 10}</TD> * <TD>{@code "Write Once, Run Anywhere"}</TD> * </TR> * <TR><TD>{@code null}</TD><TD>{@code NullPointerException}</TD></TR> * </TABLE> * * @param s This may be any {@code java.lang.String} * * @param totalStringLength If {@code s.length()} is smaller than {@code 'totalStringLength'}, * then as many space characters ({@code ' '}) as are needed to ensure that the returned * {@code 'String'} has length equal to {@code 'totalStringLength'} will be * <B><I>postpended</B></I> to the input {@code String} parameter {@code 's'}. * * <BR /><BR />If {@code s.length()} is greater than {@code 'totalStringLength'}, then the * original input shall be returned. * * @throws IllegalArgumentException If {@code totalStringLength} is zero or negative. * * @see #leftSpacePad(String, int) */ public static String rightSpacePad(String s, int totalStringLength) { if (totalStringLength <= 0) throw new IllegalArgumentException( "totalString length was '" + totalStringLength + "', " + "however it is expected to be a positive integer." ); return (s.length() >= totalStringLength) ? s : String.format("%1$-" + totalStringLength + "s", s); } /** * Runs a Regular-Expression over a {@code String} to retrieve all matches that occur between * input {@code String} parameter {@code 's'} and Regular-Expression {@code 'regEx'}. * * @param s Any Java {@code String} * @param regEx Any Java Regular-Expression * * @param eliminateOverlappingMatches When this parameter is passed {@code 'TRUE'}, successive * matches that have portions which overlap each-other are eliminated. * * @return An array of all {@code MatchResult's} (from package {@code 'java.util.regex.*'}) that * were produced by iterating the {@code Matcher's} {@code 'find()'} method. */ public static MatchResult[] getAllMatches (String s, Pattern regEx, boolean eliminateOverlappingMatches) { Stream.Builder<MatchResult> b = Stream.builder(); Matcher m = regEx.matcher(s); int prevEnd = 0; while (m.find()) { MatchResult matchResult = m.toMatchResult(); // This skip any / all overlapping matches - if the user has requested it if (eliminateOverlappingMatches) if (matchResult.start() < prevEnd) continue; b.accept(matchResult); prevEnd = matchResult.end(); } // Convert the Java-Stream into a Java-Array and return the result return b.build().toArray(MatchResult[]::new); } // ******************************************************************************************** // ******************************************************************************************** // Helper set & get for strings // ******************************************************************************************** // ******************************************************************************************** /** * This sets a character in a {@code String} to a new value, and returns a result * @param str Any java {@code String} * @param i An index into the underlying character array of that {@code String}. * @param c A new character to be placed at the <I>i'th position</I> of this {@code String}. * * @return a new java {@code String}, with the appropriate index into the {@code String} * substituted using character parameter {@code 'c'}. */ public static String setChar(String str, int i, char c) { return ((i + 1) < str.length()) ? (str.substring(0, i) + c + str.substring(i + 1)) : (str.substring(0, i) + c); } /** * This removes a character from a {@code String}, and returns a new {@code String} as a * result. * * @param str Any Java-{@code String}. * * @param i This is the index into the underlying java {@code char}-array whose character will * be removed from the return {@code String}. * * @return Since Java {@code String}'s are all immutable, this {@code String} that is returned * is completely new, with the character that was originally at index 'i' removed. */ public static String delChar(String str, int i) { if ((i + 1) < str.length()) return str.substring(0, i) + str.substring(i + 1); else return str.substring(0, i); } /** * Returns the same {@code String} is input, but trims all spaces down to a single space. * Each and every <I>lone / independent or contiguous</I> white-space character is reduced * to a single space-character. * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input String</TH><TH>Output String</TH></TR> * <TR><TD><PRE>{@code "This has extra spaces\n"}</PRE></TD> * <TD>{@code "This has extra spaces "}</TD> * </TR> * <TR><TD>{@code "This does not"}</TD> * <TD>{@code "This does not"}</TD> * </TR> * <TR><TD>{@code "\tThis\nhas\ttabs\nand\tnewlines\n"}</TD> * <TD>{@code " This has tabs and newlines "}</TD> * </TR> * </TABLE> * * @param s Any Java {@code String} * * @return A {@code String} where all white-space is compacted to a single space. This is * generally how HTML works, when it is displayed in a browser. */ public static String removeDuplicateSpaces(String s) { return StringParse.WHITE_SPACE_REGEX.matcher(s).replaceAll(" "); } /** * This string-modify method simply removes any and all white-space matches found within a * java-{@code String}. * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input String</TH><TH>Output String</TH></TR> * <TR><TD><PRE>{@code "This Has Extra Spaces\n"}</PRE></TD> * <TD>{@code "ThisHasExtraSpaces"}</TD> * </TR> * <TR><TD>{@code "This Does Not"}</TD> * <TD>{@code "ThisDoesNot"}</TD> * </TR> * <TR><TD>{@code "\tThis\nHas\tTabs\nAnd\tNewlines\n"}</TD> * <TD>{@code "ThisHasTabsAndNewlines"}</TD> * </TR> * </TABLE> * * @param s Any {@code String}, but if it has any white-space (space that matches * regular-expression: {@code \w+}) then those character-blocks will be removed * * @return A new {@code String} without any {@code \w} (RegEx for 'whitespace') * * @see #WHITE_SPACE_REGEX */ public static String removeWhiteSpace(String s) { return WHITE_SPACE_REGEX.matcher(s).replaceAll(""); } /** * Generates a {@code String} that contains {@code n} copies of character {@code c}. * @return {@code n} copies of {@code c}, as a {@code String}. * @throws IllegalArgumentException If the value passed to parameter {@code 'n'} is negative * @see StrSource#caretBeneath(String, int) */ public static String nChars(char c, int n) { if (n < 0) throw new IllegalArgumentException("Value of parameter 'n' is negative: " + n); char[] cArr = new char[n]; Arrays.fill(cArr, c); return new String(cArr); } /** * Generates a {@code String} that contains {@code n} copies of {@code s}. * @return {@code n} copies of {@code s} as a {@code String}. * @throws NException if the value provided to parameter {@code 'n'} is negative. */ public static String nStrings(String s, int n) { if (n < 0) throw new NException("A negative value was passed to 'n' [" + n + ']'); StringBuilder sb = new StringBuilder(); for (int i=0; i < n; i++) sb.append(s); return sb.toString(); } /** * This method checks whether or not a java-{@code String} has white-space. * * @param s Any Java-{@code String}. If this {@code String} has any white-space, this method * will return {@code TRUE} * * @return {@code TRUE} If there is any white-space in this method, and {@code FALSE} otherwise. * * @see #WHITE_SPACE_REGEX */ public static boolean hasWhiteSpace(String s) { return WHITE_SPACE_REGEX.matcher(s).find(); } /** * Counts the number of instances of character input {@code char c} contained by the * input {@code String s} * * @param s Any {@code String} containing any combination of ASCII/UniCode characters * * @param c Any ASCII/UniCode character. * * @return The number of times {@code char c} occurs in {@code String s} */ public static int countCharacters(String s, char c) { int count = 0; int pos = 0; while ((pos = s.indexOf(c, pos + 1)) != -1) count++; return count; } /** * If the {@code String} passed to this method contains a single-quote on both sides of the * {@code String}, or if it contains a double-quote on both sides of this {@code String}, then * this method shall return a new {@code String} that is shorter in length by 2, and leaves off * the first and last characters of the input parameter {@code String}. * * <BR /><BR /><B>HOPEFULLY,</B> The name of this method explains clearly what this method does * * @param s This may be any java {@code String}. Only {@code String's} whose first and last * characters are not only quotation marks (single or double), but also they are <B>the same, * identical, quotation marks on each side.</B> * * @return A new {@code String} that whose first and last quotation marks are gone - if they * were there when this method began. */ public static String ifQuotesStripQuotes(String s) { if (s == null) return null; if (s.length() < 2) return s; int lenM1 = s.length() - 1; // Position of the last character in the String if ( ((s.charAt(0) == '\"') && (s.charAt(lenM1) == '\"')) // String has Double-Quotation-Marks || // ** or *** ((s.charAt(0) == '\'') && (s.charAt(lenM1) == '\'')) ) // String has Single-Quotation-Marks return s.substring(1, lenM1); else return s; } /** * Counts the number of lines of text inside of a Java {@code String}. * * @param text This may be any text, as a {@code String}. * * @return Returns the number of lines of text. The integer returned shall be precisely * equal to the number of {@code '\n'} characters <B><I>plus one!</I></B> */ public static int numLines(String text) { if (text.length() == 0) return 0; int pos = -1; int count = 0; do { pos = text.indexOf('\n', pos + 1); count++; } while (pos != -1); return count; } // ******************************************************************************************** // ******************************************************************************************** // Misc Date String Functions // ******************************************************************************************** // ******************************************************************************************** /** * Converts an integer into a Month. I could just use the class {@code java.util.Calendar}, * but it is so complicated, that using an internal list is easier. * * @param month The month, as a number from {@code '1'} to {@code '12'}. * @return A month as a {@code String} like: {@code "January"} or {@code "August"} * @see #months */ public static String monthStr(int month) { return months.get(month); } /** * Generates a "Date String" using the character separator {@code '.'} * @return A {@code String} in the form: {@code YYYY.MM.DD} */ public static String dateStr() { return dateStr('.', false); } /** * Generates a "Date String" using the <I>separator</I> parameter as the separator between * numbers * * @param separator Any ASCII or UniCode character. * * @return A {@code String} of the form: {@code YYYYcMMcDD} where {@code 'c'} is the passed * {@code 'separator'} parameter. */ public static String dateStr(char separator) { return dateStr(separator, false); } /** * Generates a "Date String" that is consistent with the directory-name file-storage locations * used to store articles from {@code http://Gov.CN}. * * @return The {@code String's} used for the Chinese Government Web-Portal Translation Pages */ public static String dateStrGOVCN() { return dateStr('/', false).replaceFirst("/", "-"); } // "2017-12/05" /** * This class is primary included because although Java has a pretty reasonable "general * purpose" calendar class/interface, but a consistent / same {@code String} since is needed * because the primary use here is for building the names of files. * * @param separator Any ASCII or Uni-Code character. * * @param includeMonthName When <I>TRUE</I>, the English-Name of the month ({@code 'January'} * ... {@code 'December'}) will be appended to the month number in the returned {@code String}. * * @return The year, month, and day as a {@code String}. */ public static String dateStr(char separator, boolean includeMonthName) { Calendar c = internalCalendar; String m = zeroPad10e2(c.get(Calendar.MONTH) + 1); // January is month zero! String d = zeroPad10e2(c.get(Calendar.DAY_OF_MONTH)); if (includeMonthName) m += " - " + c.getDisplayName(Calendar.MONTH, 2, Locale.US); if (separator != 0) return c.get(Calendar.YEAR) + "" + separator + m + separator + d; else return c.get(Calendar.YEAR) + "" + m + d; } /** * Returns a {@code String} that has the year and the month (but not the day, or other time * components). * * @return Returns the current year and month as a {@code String}. */ public static String ymDateStr() { return ymDateStr('.', false); } /** * Returns a {@code String} that has the year and the month (but not the day, or other time * components). * * @param separator The single-character separator used between year, month and day. * * @return The current year and month as a {@code String}. */ public static String ymDateStr(char separator) { return ymDateStr(separator, false); } /** * Returns a {@code String} that has the year and the month (but not the day, or other time * components). * * @param separator The single-character separator used between year, month and day. * * @param includeMonthName When this is true, the name of the month, in English, is included * with the return {@code String}. * * @return YYYYseparatorMM(? include-month-name) */ public static String ymDateStr(char separator, boolean includeMonthName) { Calendar c = internalCalendar; String m = zeroPad10e2(c.get(Calendar.MONTH) + 1); // January is month zero! if (includeMonthName) m += " - " + c.getDisplayName(Calendar.MONTH, 2, Locale.US); if (separator != 0) return c.get(Calendar.YEAR) + "" + separator + m; else return c.get(Calendar.YEAR) + "" + m; } // ******************************************************************************************** // ******************************************************************************************** // Misc Time String Functions // ******************************************************************************************** // ******************************************************************************************** /** * Returns the current time as a {@code String}. * * @return military time - with AM|PM (redundant) added too. * Includes only Hour and Minute - separated by a colon character {@code ':'} * * @see #timeStr(char) */ public static String timeStr() { return timeStr(':'); } /** * Returns the current time as a {@code String}. * * @param separator The character used to separate the minute & hour fields * * @return military time - with AM|PM added redundantly, and a separator of your choosing. */ public static String timeStr(char separator) { Calendar c = internalCalendar; int ht = c.get(Calendar.HOUR) + ((c.get(Calendar.AM_PM) == Calendar.AM) ? 0 : 12); String h = zeroPad10e2((ht == 0) ? 12 : ht); // 12:00 is represented as "0"... changes this... String m = zeroPad10e2(c.get(Calendar.MINUTE)); String p = (c.get(Calendar.AM_PM) == Calendar.AM) ? "AM" : "PM"; if (separator != 0) return h + separator + m + separator + p; else return h + m + p; } /** * Returns the current time as a {@code String}. This method uses all time components * available. * * @return military time - with AM|PM added redundantly. */ public static String timeStrComplete() { Calendar c = internalCalendar; int ht = c.get(Calendar.HOUR) + ((c.get(Calendar.AM_PM) == Calendar.AM) ? 0 : 12); String h = zeroPad10e2((ht == 0) ? 12 : ht); // 12:00 is represented as "0" String m = zeroPad10e2(c.get(Calendar.MINUTE)); String s = zeroPad10e2(c.get(Calendar.SECOND)); String ms = zeroPad(c.get(Calendar.MILLISECOND)); String p = (c.get(Calendar.AM_PM) == Calendar.AM) ? "AM" : "PM"; return h + '-' + m + '-' + p + '-' + s + '-' + ms + "ms"; } /** * The words "ordinal indicator" are referring to the little character {@code String} that is * often used in English to make a number seem more a part of an english sentence. * * @param i Any positive integer (greater than 0) * * @return This will return the following strings: * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input: </TH><TH>RETURNS:</TH></TR> * <TR><TD>i = 1 </TD><TD>"st" (as in "1st","first") </TD></TR> * <TR><TD>i = 2 </TD><TD>"nd" (as in "2nd", "second") </TD></TR> * <TR><TD>i = 4 </TD><TD>"th" (as in "4th") </TD></TR> * <TR><TD>i = 23 </TD><TD>"rd" (as in "23rd") </TD></TR> * </TABLE> * * @throws IllegalArgumentException If i is negative, or zero */ public static String ordinalIndicator(int i) { if (i < 1) throw new IllegalArgumentException("i: " + i + "\tshould be a natural number > 0."); // Returns the last 2 digits of the number, or the number itself if it is less than 100. // Any number greater than 100 - will not have the "text-ending" (1st, 2nd, 3rd..) affected // by the digits after the first two digits. Just analyze the two least-significant digits i = i % 100; // All numbers between "4th" and "19th" end with "th" if ((i > 3) && (i < 20)) return "th"; // set i to be the least-significant digit of the number - if that number was 1, 2, or 3 i = i % 10; // Obvious: English Rules. if (i == 1) return "st"; if (i == 2) return "nd"; if (i == 3) return "rd"; // Compiler is complaining. This statement should never be executed. return "th"; } // ******************************************************************************************** // ******************************************************************************************** // Zero Padding stuff // ******************************************************************************************** // ******************************************************************************************** /** * This just zero-pads integers with "prepended" zero's. java.text has all kinds of extremely * intricate zero-padding and text-formatting classes. However, here, these are generally used * for <B>debug, line-number, or count</B> information that is printed to the UNIX terminal. * When this is the case, a simple and easily remembered <I>'one line method'</I> is a lot more * useful than all of the highly-scalable versions of the text-formatting classes in java.text. * * @param n Any Integer. If {@code 'n'} is negative or greater than 1,000 - then null is * returned. * * @return A zero-padded {@code String} - <B><I>to precisely three orders of 10</I></B>, as in * the example table below: * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input </TH><TH><I>RETURNS:</I></TH></TR> * <TR><TD>n = 9 </TD><TD>"009"</TD></TR> * <TR><TD>n = 99 </TD><TD>"099"</TD></TR> * <TR><TD>n = 999 </TD><TD>"999"</TD></TR> * <TR><TD>n = 9999 </TD><TD>null</TD></TR> * <TR><TD>n = -10 </TD><TD>null</TD></TR> * </TABLE> * * @see #zeroPad10e2(int) * @see #zeroPad10e4(int) */ public static String zeroPad(int n) { if (n < 0) return null; if (n < 10) return "00" + n; if (n < 100) return "0" + n; if (n < 1000) return "" + n; return null; } /** * Pads an integer such that it contains enough leading zero's to ensure a String-length of * two. * * @param n Must be an integer between 0 and 99, or else null will be returned * * @return A zero-padded String of the integer, <B><I>to precisely two orders of * 10</I></B><BR />. Null is returned if the number cannot fit within two spaces. Example * table follows: * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input </TH><TH><I>RETURNS:</I></TH></TR> * <TR><TD>n = 9 </TD><TD>"09"</TD></TR> * <TR><TD>n = 99 </TD><TD>"99"</TD></TR> * <TR><TD>n = 999 </TD><TD>null</TD></TR> * <TR><TD>n = -10 </TD><TD>null</TD></TR> * </TABLE> * * @see #zeroPad(int) */ public static String zeroPad10e2(int n) { if (n < 0) return null; if (n < 10) return "0" + n; if (n < 100) return "" + n; return null; } /** * Pads an integer such that it contains enough leading zero's to ensure a String-length of * four. * * @param n Must be an integer between 0 and 9999, or else null will be returned * * @return A zero-padded String of the integer, <B><I>to precisely four orders of 10</I></B>. * Null is returned if the number cannot fit within four spaces. Example table follows: * * <TABLE CLASS=JDBriefTable> * <TR><TH>Input </TH><TH><I>RETURNS:</I></TH></TR> * <TR><TD>n = 9 </TD><TD>"0009"</TD></TR> * <TR><TD>n = 99 </TD><TD>"0099"</TD></TR> * <TR><TD>n = 999 </TD><TD>"0999"</TD></TR> * <TR><TD>n = 9999 </TD><TD>"9999" </TD></TR> * <TR><TD>n = 99999 </TD><TD>null</TD></TR> * <TR><TD>n = -10 </TD><TD>null</TD></TR> * </TABLE> * * @see #zeroPad(int) */ public static String zeroPad10e4(int n) { if (n < 0) return null; if (n < 10) return "000" + n; if (n < 100) return "00" + n; if (n < 1000) return "0" + n; if (n < 10000) return "" + n; return null; } /** * Pad's an integer with leading zeroes into a {@code String}. The number of zeroes padded is * equal to parameter {@code 'powerOf10'}. If {@code int 'powerOf10'} were equal to zero, then * any integer passed to this function would return a {@code String} that was precisely three * characters long. If the value of parameter {@code int 'n'} were larger than {@code 1,000} * or negative, then null would be returned. * * @param n Must be an integer between {@code '0'} and {@code '9999'} where the number of * {@code '9'} digits is equal to the value of parameter {@code int 'powerOf10'} * * @param powerOf10 This must be a positive integer greater than {@code '1'}. It may not be * larger {@code '11'}. The largest value that any integer in Java may attain is * {@code '2,147,483, 647'} * * @return A zero padded {@code String}. If a negative number is passed to parameter * {@code 'n'}, then 'null' shall be returned. Null shall also be returned if the "Power of 10 * Exponent of parameter {@code n}" is greater than the integer-value of parameter * {@code 'powerOf10'} * * <BR /><BR /><B>FOR INSTANCE:</B> a call to: {@code zeroPad(54321, 4);} would return null * since the value of parameter {@code 'n'} has five-decimal-places, but {@code 'powerOf10'} is * only 4! * * @throws IllegalArgumentException if the value parameter {@code 'powerOf10'} is less than 2, * or greater than {@code 11}. */ public static String zeroPad(int n, int powerOf10) { if (n < 0) return null; // Negative Values of 'n' not allowed char[] cArr = new char[powerOf10]; // The String's length will be equal to 'powerOf10' String s = "" + n; // (or else 'null' would be returned) int i = powerOf10 - 1; // Internal Loop variable int j = s.length() - 1; // Internal Loop variable Arrays.fill(cArr, '0'); // Initially, fill the output char-array with all // zeros while ((i >= 0) && (j >= 0)) // Now start filling that char array with the cArr[i--] = s.charAt(j--); // actual number if (j >= 0) return null; // if all of parameter 'n' was inserted into the // output (number 'n' didn't fit) then powerOf10 // was insufficient, so return null. return new String(cArr); } // ******************************************************************************************** // ******************************************************************************************** // Find / Front Last-Front-Slash // ******************************************************************************************** // ******************************************************************************************** /** * This function finds the position of the last "front-slash" character {@code '/'} in a * java-{@code String} * * @param urlOrDir This is any java-{@code String}, but preferably one that is a * {@code URL}, or directory. * * @return The {@code String}-index of the last 'front-slash' {@code '/'} position in a * {@code String}, or {@code -1} if there are not front-slashes. */ public static int findLastFrontSlashPos(String urlOrDir) { return urlOrDir.lastIndexOf('/'); } /** * This returns the contents of a {@code String}, after the last front-slash found. * * <BR /><BR /><B>NOTE:</B> If not front-slash {@code '/'} character is found, then the * original {@code String} is returned. * * @param urlOrDir This is any java-{@code String}, but preferably one that is a * {@code URL}, or directory. * * @return the portion of the {@code String} after the final front-slash {@code '/'} character. * If there are no front-slash characters found in this {@code String}, then the original * {@code String} shall be returned. */ public static String fromLastFrontSlashPos(String urlOrDir) { int pos = urlOrDir.lastIndexOf('/'); if (pos == -1) return urlOrDir; return urlOrDir.substring(pos + 1); } /** * This returns the contents of a {@code String}, before the last front-slash found (including * the front-slash {@code '/'} itself). * * <BR /><BR /><B>NOTE:</B> If no front-slash {@code '/'} character is found, then null is * returned. * * @param urlOrDir This is any java-{@code String}, but preferably one that is a * {@code URL}, or directory. * * @return the portion of the {@code String} <I><B>before and including</B></I> the final * front-slash {@code '/'} character. If there are no front-slash characters found in this * {@code String}, then null. */ public static String beforeLastFrontSlashPos(String urlOrDir) { int pos = urlOrDir.lastIndexOf('/'); if (pos == -1) return null; return urlOrDir.substring(0, pos + 1); } // ******************************************************************************************** // ******************************************************************************************** // Find / From Last-File-Separator // ******************************************************************************************** // ******************************************************************************************** /** * This function finds the position of the last {@code 'java.io.File.separator'} character in a * java-{@code String}. In UNIX-based systems, this is a forward-slash {@code '/'} character, * but in Windows-MSDOS, this is a back-slash {@code '\'} character. Identifying which of the * two is used is obtained by "using" Java's {@code File.separator} class and field. * * @param fileOrDir This may be any Java-{@code String}, but preferably one that represents a * file or directory. * * @return The {@code String}-index of the last 'file-separator' position in a {@code String}, * or {@code -1} if there are no such file-separators. */ public static int findLastFileSeparatorPos(String fileOrDir) { return fileOrDir.lastIndexOf(File.separator.charAt(0)); } /** * This returns the contents of a {@code String}, after the last * {@code 'java.io.File.separator'} found. * * <BR /><BR /><B>NOTE:</B> If no {@code 'java.io.File.separator'} character is found, then * the original {@code String} is returned. * * @param fileOrDir This is any java-{@code String}, but preferably one that is a filename or * directory-name * * @return the portion of the {@code String} after the final {@code 'java.io.File.separator'} * character. If there are no such characters found, then the original {@code String} shall * be returned. */ public static String fromLastFileSeparatorPos(String fileOrDir) { int pos = fileOrDir.lastIndexOf(File.separator.charAt(0)); if (pos == -1) return fileOrDir; return fileOrDir.substring(pos + 1); } /** * This returns the contents of a {@code String}, before the last * {@code 'java.io.File.separator'} (including the separator itself). * * <BR /><BR /><B>NOTE:</B> If no {@code 'java.io.File.separator'} character is found, * then null is returned. * * @param urlOrDir This is any java-{@code String}, but preferably one that is a * {@code URL}, or directory. * * @return the portion of the {@code String} <I><B>before and including</B></I> the final * {@code 'java.io.File.separator'} character. If there are no such characters found in this * {@code String}, then null is returned. */ public static String beforeLastFileSeparatorPos(String urlOrDir) { int pos = urlOrDir.lastIndexOf(File.separator.charAt(0)); if (pos == -1) return null; return urlOrDir.substring(0, pos + 1); } // ******************************************************************************************** // ******************************************************************************************** // Find / From File-Extension // ******************************************************************************************** // ******************************************************************************************** /** * This method swaps the ending 'File Extension' with another, parameter-provided, * extension. * * @param fileNameOrURLWithExtension Any file-name (or {@code URL}) that has an extension. * * @param newExtension The file or {@code URL} extension used as a substitute for the old * extension. This {@code String} may begin with the dot / period character ({@code '.'}), * and if it does not, one wil be appended. * * @return The new file-name or {@code URL} having the substituted extension. * * @throws StringFormatException If the {@code String} passed does not have any * {@code '.'} (period) characters, then this exception will throw. * * <BR /><BR /><B STYLE='color:red'>CAUTION:</B> In lieu of an exhaustive check on whether * or not the input file-name is a valid name, this method will simply check for the presence * or absence of a period-character ({@code '.'}). <I>Checking the validity of the input name * is <B>far</B> beyond the scope of this method.</I> * * <BR /><BR /><B>ALSO:</B> This method shall check to ensure that the {@code 'newExtension'} * parameter does not have length zero. * * <BR /><BR />To remove a file-extension, use {@link #removeExtension(String)} */ public static String swapExtension(String fileNameOrURLWithExtension, String newExtension) { int dotPos = fileNameOrURLWithExtension.lastIndexOf('.'); if (dotPos == -1) throw new StringFormatException( "The file-name provided\n[" + fileNameOrURLWithExtension + "]\n" + "does not have a file-extension" ); if (newExtension.length() == 0) throw new StringFormatException( "The new file-name extension has length 0. " + " To remove an extension, use 'StringParse.removeFileExtension(fileName)'" ); return (newExtension.charAt(0) == '.') ? fileNameOrURLWithExtension.substring(0, dotPos) + newExtension : fileNameOrURLWithExtension.substring(0, dotPos) + '.' + newExtension; } /** * This method simply removes all character data after the last identified period character * ({@code '.'}) found within {@code fileNameOrURL}. * * <BR /><BR />If the input-{@code String} does not have a period-character, the original * {@code String} will be returned, unmodified. * * @param fileNameOrURL Any file-name or {@code URL}, as a {@code String}. * * @return The modified file-name, or {@code URL}, as a {@code String}. * * <BR /><BR /><B STYLE='color:red'>NOTE:</B> No validity checks <I>of any kind</I> are * performed on {@code 'fileNameOrURL'}. This method merely checks for the presence or * absence of a {@code '.'} (period-character), and if it finds one, removes everything * after-and-including the last-period. */ public static String removeExtension(String fileNameOrURL) { int dotPos = fileNameOrURL.lastIndexOf('.'); if (dotPos == -1) return fileNameOrURL; return fileNameOrURL.substring(0, dotPos); } /** * This will return the location within a {@code String} where the last period ({@code '.'}) * is found. * * <BR /><BR /><B>ALSO:</B> No validity checks for valid file-system names are performed. * Rather, the portion of the input-{@code String} starting at the location of the last period * is returned, regardless of what the {@code String} contains. * * @param file This may be any Java-{@code String}, but preferably one that represents a * file. * * @param includeDot When this parameter is passed {@code TRUE}, the position-index that is * returned will be the location of the last index where a period ({@code '.'}) is found. * When {@code FALSE}, the index returned will be the location of that period {@code + 1}. * * @return This will return the location of the file-extension. If no period is found, then * {@code -1} is returned. If the period is the last {@code char} in the {@code String}, * and parameter {@code 'includeDot'} is {@code FALSE}, then {@code -1} is returned. */ public static int findExtension(String file, boolean includeDot) { int pos = file.lastIndexOf('.'); if (pos == -1) return -1; if (includeDot) return pos; pos++; return (pos < file.length()) ? pos : -1; } /** * This returns the contents of a {@code String}, after the last period {@code '.'} in that * {@code String}. For file-system and web files, this is often referred to as the <B>file * extension.</B> * * <BR /><BR /><B>NOTE:</B> If no period {@code '.'} character is found, then null is returned. * * <BR /><BR /><B>ALSO:</B> No validity checks for valid file-system names are performed. * Rather, the portion of the input-{@code String} starting at the location of the last period * is returned, regardless of what the {@code String} contains. * * @param file This is any java-{@code String}, but preferably one that is a filename. * * @param includeDot This determines whether the period {@code '.'} is to be included in the * returned-{@code String}. * * @return the portion of the {@code String} after the final period {@code '.'} character. * If parameter {@code includeDot} has been passed {@code FALSE}, then the portion of the * input-{@code String} beginning after the last period is returned. * * <BR /><BR />If there are no period characters found in this {@code String}, then null * is returned. */ public static String fromExtension(String file, boolean includeDot) { int pos = findExtension(file, includeDot); if (pos == -1) return null; return file.substring(pos); } /** * This returns the contents of a {@code String}, before the last period {@code '.'} in that * {@code String}. For file-system and web files, this is often referred to as the <B>file * extension.</B> * * <BR /><BR /><B>NOTE:</B> If no period {@code '.'} character is found, then the original * {@code String} is returned. * * <BR /><BR /><B>ALSO:</B> No validity checks for valid file-system names are performed. * Rather, the portion of the input-{@code String} starting at the location of the last period * is returned, regardless of what the {@code String} contains. * * @param file This is any java-{@code String}, but preferably one that is a filename. * * @return the portion of the {@code String} before the final period {@code '.'} character. * * <BR /><BR />If there are no period characters found in this {@code String}, then the * original file is returned. */ public static String beforeExtension(String file) { int pos = file.lastIndexOf('.'); if (pos == -1) return file; return file.substring(0, pos); } /** * This function returns the root URL-directory of a {@code String} * * <BR /><BR /><B>SPECIFICALLY:</B> it searches for the "last forward slash" in a * {@code String}, and returns a substring from position 0 to that point. If there aren't any * forward slashes in this {@code String}, null is returned. The front-slash itself is * included in the returned {@code String}. * * <BR /><BR /><B>NOTE:</B> It is similar to the old MS-DOS call to "DIR PART" * * @param url Any {@code String} that is intended to be an "Internet URL" - usually * http://domain/directory/[file] * * @return substring(0, index of last front-slash ({@code '/'}) in {@code String}) */ public static String findURLRoot(String url) { int pos = findLastFrontSlashPos(url); if (pos == -1) return null; else return url.substring(0, pos + 1); } /** * * @return After breaking the {@code String} by white-space, this returns the first 'chunk' * before the first whitespace. */ public static String firstWord(String s) { int pos = s.indexOf(" "); if (pos == -1) return s; else return s.substring(0, pos); } // ******************************************************************************************** // ******************************************************************************************** // Removing parts of a string // ******************************************************************************************** // ******************************************************************************************** /** * This function will remove any pairs of Brackets within a {@code String}, and returned the * paired down {@code String} * * @param s Any {@code String}, which may or may not contain a "Bracket Pair" * * <BR /><BR /><B>For Example:</B> * * <BR /><BR /> * * <UL CLASS=JDUL> * <LI>This {@code String} does contain [a pair of brackets] within!</LI> * <LI>But this {@code String} does not.</LI> * </UL> * * @return The same {@code String}, but with any bracket-pairs removed. */ public static String removeBrackets(String s) { return remove_(s, '[', ']'); } /** * Functions the same as {@code removeBrackets(String)} - but removes pairs of curly-braces, * instead<BR /> <B>NOTE:</B>These are { curly braces } that will be removed by this * {@code String}! * * @param s Any valid {@code String} { such as } - <I>(even this {@code String})</I>. * * <BR /><BR /><B>For Example:</B> * * <BR /><BR /> * * <UL CLASS=JDUL> * <LI>This {@code String} does contain {a pair of curly-braces} within!</LI> * <LI>But this {@code String} does not.</LI> * </UL> * * @return The same {@code String}, but with any curly-brace-pairs removed. * * @see #removeBrackets(String) */ public static String removeBraces(String s) { return remove_(s, '{', '}'); } /** * Removes Parenthesis, similar to other parenthetical removing functions. * * @param s Any (valid) {@code String}. Below are sample inputs: * * <BR /><BR /><UL CLASS=JDUL> * <LI>This {@code String} does contain (a pair of parenthesis) within!</LI> * <LI>But this {@code String} does not.</LI> * </UL> * * @return The same {@code String}, but with any parenthesis removed. * * @see #removeBrackets(String) */ public static String removeParens(String s) { return remove_(s, '(', ')'); } /** * Removes all parenthetical notations. Calls all <I><B>remove functions</B></I> * * @param s Any valid string * * @return The same string, but with all parenthesis, curly-brace & bracket pairs removed. * * @see #removeParens(String) * @see #removeBraces(String) * @see #removeBrackets(String) */ public static String removeAllParenthetical(String s) { return removeParens(removeBraces(removeBrackets(s))); } private static String remove_(String s, char left, char right) { int p = s.indexOf(left); if (p == -1) return s; String ret = s.substring(0, p).trim(); for (++p; (s.charAt(p) != right) && (p < s.length()); p++); if (p >= (s.length() - 1)) return ret; ret += " " + s.substring(p + 1).trim(); if (ret.indexOf(left) != -1) return remove_(ret.trim(), left, right); else return ret.trim(); } // ******************************************************************************************** // ******************************************************************************************** // Base-64 Encoded Java Objects // ******************************************************************************************** // ******************************************************************************************** /** * This will convert any Serializable Java Object into a base-64 String. This {@code String} * may be saved, transmitted, <I>even e-mailed to another party, if you wish</I> and decoded * else-where. * * <BR /><BR /><B>REQUIREMENTS:</B> * * <BR /><BR /><OL CLASS=JDOL> * <LI> Object must implement the {@code interface java.io.Serializable}</LI> * * <LI> Receiving party or storage-device must have access to the {@code .jar file, or .class * file(s)} needed to instantiate that object! <I>(You must have shared your classes if * you intend to let other people de-serialize instances of that class)</I> * </LI> * </OL> * * @param o Any java {@code java.lang.Object}. This object must be Serializable, or else the * code will generate an exception. * * @return A {@code String} version of this object. It will be: * * <BR /><BR /><OL CLASS=JDOL> * <LI> Serialized using the {@code java.io.ObjectOutputStream(...)} <I>object-serialization * method</I> * </LI> * * <LI> Compressed using the {@code java.io.GZIPOutputStream(...)} <I>stream-compression * method</I> * </LI> * <LI>Encoded to a {@code String}, via Base-64 Encoding * {@code java.util.Base64.getEncoder()}</LI> * </OL> * * <BR /><B><SPAN STYLE="color: red">NOTE:</B></SPAN> Compression does not always make much * difference, however often times when doing web-scraping projects, there are large Java * {@code java.util.Vector<String>} filled with many lines of text, and these lists may be * instantly and easily saved using object-serialization. Furthermore, in these cases, the * compression will sometimes reduce file-size by an order of magnitude. * * @see #b64StrToObj(String) */ public static String objToB64Str(Object o) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); ObjectOutputStream oos = new ObjectOutputStream(gzip); oos.writeObject(o); oos.flush(); gzip.finish(); oos.close(); bos.close(); return Base64.getEncoder().encodeToString(bos.toByteArray()); } /** * This converts <B><I>to</B></I> any <I><B>java.io.Serializable</B></I> object * <I><B>from</B></I> a compressed, serialized, Base-64 Encoded {@code java.lang.String}. This * method can be thought of as one which converts objects which have been previously encoded as * a {@code String}, and possibly even transmitted across the internet, back into an Java * {@code Object}. * * <BR /><BR /><B>REQUIREMENTS:</B> The {@code Object} that is to be instantiated must have its * class files accessible to the class-loader. This is the exact-same requirement expected by * all Java "de-serializations" routines. * * @param str Any previously Base-64 encoded, serialized, compressed {@code java.lang.Object'} * that has been saved as a {@code String}. That {@code String} should have been generated * using the {@code Programming.objToB64Str(Object o)} method in this class. * * <BR /><BR /><OL CLASS=JDOL> * <LI>Serialized using the {@code java.io.ObjectOutputStream(...)} <I>object-serialization * method</I></LI> * <LI>Compressed using the {@code java.io.GZIPOutputStream(...)} <I>sream-compression * method</I></LI> * <LI>Encoded to a {@code String}, via Base-64 Encoding * {@code java.util.Base64.getEncoder()}</LI> * </OL> * * <BR /><B><SPAN STYLE="color: red">NOTE:</B></SPAN> Compression does not always make much * difference, however often times when doing web-scraping projects, there are large Java * {@code java.util.Vector<String>} filled with many lines of text, and these lists may be * instantly and easily saved using object-serialization. Furthermore, in these cases, the * compression will sometimes reduce file-size by an order of magnitude. * * @return The de-compressed {@code java.lang.Object} converted back from a {@code String}. * * @see #objToB64Str(Object) */ public static Object b64StrToObj(String str) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(str)); GZIPInputStream gzip = new GZIPInputStream(bis); ObjectInputStream ois = new ObjectInputStream(gzip); Object ret = null; try { ret = ois.readObject(); } catch (ClassNotFoundException e) { throw new IOException( "There were no serialized objects found in your String. See e.getCause();", e ); } bis.close(); ois.close(); return ret; } /** * This performs an identical operation as the method: {@code objToB64Str}, however it * generates an output {@code String} that is "MIME" compatible. All this means is that the * {@code String} itself - <I>which could conceivable by thousands or even hundreds of * thousands of characters long</I> - will have {@code new-line characters} inserted such that * it may be printed on paper or included in a text-file that is (slightly) more * human-readable. Base64 MIME encoded {@code String's} look like very long paragraphs of * random-text data, while regular Base64-encodings are a single, very-long, {@code String} * with no space characters. * * @param o Any {@code java.lang.Object}. This object must be Serializable, or else the code * will generate an exception. * * @return A Base-64 MIME Encoded {@code String} version of any serializable * {@code java.lang.Object}. * * @see #objToB64Str(Object) * @see #b64MimeStrToObj(String) */ public static String objToB64MimeStr(Object o) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); ObjectOutputStream oos = new ObjectOutputStream(gzip); oos.writeObject(o); oos.flush(); gzip.finish(); oos.close(); bos.close(); return Base64.getMimeEncoder().encodeToString(bos.toByteArray()); } /** * This performs an identical operation as the method: {@code b64StrToObj}, however receives a * "MIME" compatible encoded {@code String}. All this means is that the {@code String} itself * - <I>which could conceivable by thousands or even hundreds of thousands of characters * long</I> - will have {@code new-line characters} inserted such that it may be printed on * paper or included in a text-file that is (slightly) more human-readable. Base64 MIME * encoded {@code String's} look like very long paragraphs of random-text data, while regular * Base64 encodings a single, very-long, {@code String's}. * * @return The (de-serialized) java object that was read from the input parameter * {@code String 'str'} * * <BR /><BR /><B>REQUIREMENTS:</B> The object that is to be instantiated must have its class * files accessible to the class-loader. This is the exact-same requirement expected by all * Java "de-serializations" routines. * * @see #b64StrToObj(String) * @see #objToB64MimeStr(Object) */ public static Object b64MimeStrToObj(String str) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getMimeDecoder().decode(str)); GZIPInputStream gzip = new GZIPInputStream(bis); ObjectInputStream ois = new ObjectInputStream(gzip); Object ret = null; try { ret = ois.readObject(); } catch (ClassNotFoundException e) { throw new IOException( "There were no serialized objects found in your String. See e.getCause();", e ); } bis.close(); ois.close(); return ret; } // ******************************************************************************************** // ******************************************************************************************** // '../' (Parent Directory) // ******************************************************************************************** // ******************************************************************************************** /** * Computes a "relative {@code URL String}". * * @param fileName This is a fileName whose ancestor directory needs to be * <I>'relative-ised'</I> * * @param ancestorDirectory This is an ancestor (container) directory. * * @param separator The separator character used to separate file-system directory names. * * @return This shall return the "../.." structure needed to insert a relative-{@code URL} or * link into a web-page. * * @throws IllegalArgumentException This exception shall throw if the separator character is * not one of the standard file & directory separators: forward-slash {@code '/'} or * back-slash {@code '\'}. * * <BR /><BR />This exception also throws if the {@code String} provided to parameter * {@code 'fileName'} does not begin-with the {@code String} provided to parameter * {@code 'ancestorDirectory'}. */ public static String dotDots(String fileName, String ancestorDirectory, char separator) { if ((separator != '/') && (separator != '\\')) throw new IllegalArgumentException( "The separator character provided to this method must be either a forward-slash '/' " + "or a back-slash ('\\') character. You have provided: ['" + separator + "']." ); if (! fileName.startsWith(ancestorDirectory)) throw new IllegalArgumentException( "The file-name you have provided [" + fileName + "] is a String that does " + "start with the ancestorDirectory String [" + ancestorDirectory + "]. " + "Therefore there is no relative path using the dot-dot construct to the named " + "ancestor directory fromm the directory where the named file resides." ); int levelsDeep = StringParse.countCharacters(fileName, separator) - StringParse.countCharacters(ancestorDirectory, separator); String dotDots = ""; while (levelsDeep-- > 0) dotDots = dotDots + ".." + separator; return dotDots; } /** * Convenience Method. * <BR />Invokes: {@link #dotDotParentDirectory(String, char, short)} * <BR />Converts: {@code URL} to {@code String}, eliminates non-essential * {@code URI}-information (Such as: {@code ASP, JSP, PHP Query-Strings, and others too}) * <BR />Passes: {@code char '/'}, the separator character used in {@code URL's} * <BR />Passes: {@code '1'} to parameter {@code 'nLevels'} - only going up on directory */ public static String dotDotParentDirectory(URL url) { String urlStr = url.getProtocol() + "://" + url.getHost() + url.getPath(); return dotDotParentDirectory(urlStr, '/', (short) 1); } /** * Convenience Method. * <BR />Invokes: {@link #dotDotParentDirectory(String, char, short)} * <BR />Passes: {@code char '/'}, the separator character used in {@code URL's} * <BR />Passes: {@code '1'} to parameter {@code 'nLevels'} - only going up on directory */ public static String dotDotParentDirectory(String urlAsStr) { return dotDotParentDirectory(urlAsStr, '/', (short) 1); } /** * Convenience Method. * <BR />Invokes: {@link #dotDotParentDirectory(String, char, short)} * <BR />Converts: {@code URL} to {@code String}, eliminates non-essential * {@code URI}-information (Such as: {@code ASP, JSP, PHP Query-Strings, and others too}) * <BR />Passes: {@code char '/'}, the separator character used in {@code URL's} */ public static String dotDotParentDirectory(URL url, short nLevels) { String urlStr = url.getProtocol() + "://" + url.getHost() + url.getPath(); return dotDotParentDirectory(urlStr, '/', nLevels); } /** * Convenience Method. * <BR />Invokes: {@link #dotDotParentDirectory(String, char, short)} * <BR />Passes: {@code char '/'}, the separator character used in {@code URL's} */ public static String dotDotParentDirectory(String urlAsStr, short nLevels) { return dotDotParentDirectory(urlAsStr, '/', nLevels); } /** * Convenience Method. * <BR />Invokes: {@link #dotDotParentDirectory(String, char, short)}. * <BR />Passes: {@code '1'} to parameter {@code nLevels} - only going up one directory. */ public static String dotDotParentDirectory(String directoryStr, char dirSeparator) { return dotDotParentDirectory(directoryStr, dirSeparator, (short) 1); } /** * This does traverses up a directory-tree structure, and returns a 'parent-level' directory * that is {@code 'nLevels'} up the tree. * * <BR /><BR /><B>NOTE:</B> The character used as the "File Separator" and/or "Directory * Separator" can be obtained using the field: {@code java.io.File.Separator.charAt(0).} The * class {@code java.io.File} provides access to the file-separator used by the file-system on * which the JVM is currently running, although it treats it as a multi-character * {@code String}. Just use the commonly-used java method {@code 'charAt(0)'} to obtain the * forward-slash {@code '/'} or backward-slash {@code '\'} character. * * <BR /><BR /><B><SPAN STYLE="color: red;">IMPORTANT:</B></SPAN> There is no error-checking * performed by this method regarding whether the input {@code String} represents a valid file * or directory. Instead, this method just looks for the <I><B>second from last * separator-character (usually a {@code '/'} forward-slash char)</B></I> and returns a * substring that starts at index 0, and continues to that position-plus-1 (in order to include * that second-to-last separator char). * * @param directoryStr This may be any java-{@code String}, although it is expected to be on * which represents the file & directory structure of file on the file-system. It may also * be {@code URL} for a web-site * * @param separator This is the separator currently used by that file & directory system. * If trying to find the parent directory of a {@code URL}, this should be the forward-slash * character {@code '/'}. * * @param nLevels This is how many "parent-level directories" (how many levels up the tree) * need to be computed. This parameter must '1' or greater. If the passed parameter * {@code 'directoryStr'} does not contain enough directories to traverse up the tree, then * this method will throw an {@code IllegalArgumentException}. * * @return a {@code String} that represents 'nLevels' up the directory tree, either for * a directory on the local-file system, or on a web-server from a Uniform Resource * Locator. * * @throws IllegalArgumentException If the value of parameter {@code short 'nLevels'} is * negative, or does not identify a number consistent with the number of directories that are * contained by the input urlAsStr parameter. * * <BR /><BR />This exception shall also throw if the {@code 'separator'} character is not one * of the standard file & directory separators: forward-slash {@code '/'} or back-slash * {@code '\'}. */ public static String dotDotParentDirectory(String directoryStr, char separator, short nLevels) { if (nLevels < 1) throw new IllegalArgumentException( "The parameter nLevels may not be less than 1, nor negative. You have passed: " + nLevels ); if ((separator != '/') && (separator != '\\')) throw new IllegalArgumentException( "The separator character provided to this method must be either a forward-slash '/' " + "or a back-slash ('\\') character. You have provided: ['" + separator + "']." ); int count = 0; for (int i=directoryStr.length() - 1; i >= 0; i--) if (directoryStr.charAt(i) == separator) if (++count == (nLevels + 1)) return directoryStr.substring(0, i + 1); throw new IllegalArgumentException( "The parameter nLevels was: " + nLevels + ", but unfortunately there only were: " + count + "'" + separator + "' characters found in the directory-string." ); } // ******************************************************************************************** // ******************************************************************************************** // Quick 'isNumber' methods // ******************************************************************************************** // ******************************************************************************************** /** * Determines, efficiently, whether an input {@code String} is also an integer. * * <BR /><BR /><B>NOTE:</B> A leading plus-sign ({@code '+'}) will, in fact, generate a * {@code FALSE} return-value for this method. * * @param s Any java {@code String} * * @return {@code TRUE} if the input {@code String} is any integer, and false otherwise. * * <BR /><BR /><B>NOTE:</B> This method does not check whether the number, itself, will * actually fit into a field or variable of type {@code 'int'}. For example, the input * {@code String '12345678901234567890'} (a very large integer), though an integer from a * mathematical perspective, is not a valid java {@code 'int'}. In such cases, {@code TRUE} * is returned, but if Java's {@code Integer.parseInt} method were subsequently used, that * method would throw an exception. * * <BR /><BR /><B>NOTE:</B> The primary purpose of this method is to avoid having to write * {@code try {} catch (NumberFormatException)} code-blocks. Furthermore, if only a check * is desired, and the {@code String} does not actually need to be converted to a number, * this is also more efficient than actually performing the conversion. * * @see #isInt(String) */ public static boolean isInteger(String s) { if (s == null) return false; int length = s.length(); if (length == 0) return false; int i = 0; if (s.charAt(0) == '-') { if (length == 1) return false; i = 1; } while (i < length) { char c = s.charAt(i++); if (c < '0' || c > '9') return false; } return true; } /** * Convenience Method. * <BR />Invokes: {@link #isOfPrimitiveType(String, char[])} * <BR />Passes: The ASCII characters that comprise {@code Integer.MIN_VALUE} */ public static boolean isInt(String s) { return isOfPrimitiveType(s, INT_MIN_VALUE_DIGITS_AS_CHARS); } /** * Convenience Method. * <BR />Invokes: {@link #isOfPrimitiveType(String, char[])} * <BR />Passes: The ASCII characters that comprise {@code Long.MIN_VALUE} */ public static boolean isLong(String s) { return isOfPrimitiveType(s, LONG_MIN_VALUE_DIGITS_AS_CHARS); } /** * Convenience Method. * <BR />Invokes: {@link #isOfPrimitiveType(String, char[])} * <BR />Passes: ASCII characters that comprise {@code Byte.MIN_VALUE} */ public static boolean isByte(String s) { return isOfPrimitiveType(s, BYTE_MIN_VALUE_DIGITS_AS_CHARS); } /** * Convenience Method. * <BR />Invokes: {@link #isOfPrimitiveType(String, char[])} * <BR />Passes: ASCII characters that comprise {@code Short.MIN_VALUE} */ public static boolean isShort(String s) { return isOfPrimitiveType(s, SHORT_MIN_VALUE_DIGITS_AS_CHARS); } /** * Determines whether the input {@code String} is an integer in the range of Java's primitive * type specified by an input {@code char[]} array parameter. Specifically, if the the input * {@code String} is both a mathematical integer, and also an integer in the range of * {@code MIN_VALUE} and {@code MAX_VALUE} for that primitive-type and then (and only then) * will {@code TRUE} be returned. * * <BR /><BR /><B>NOTE:</B> The max and min values in which the range of valid integers * <B><I>must reside</I></B> (for primitive-type {@code 'int'}, for instance) are as below: * {@code -2147483648} ... {@code 2147483647}. * * <BR /><BR /><B>ALSO:</B> A leading plus-sign ({@code '+'}) will, in fact, generate a * {@code FALSE} return-value for this method. * * @param s Any Java {@code String} * * @param minArr The value of a Java Primitive {@code MIN_VALUE}, without the minus-sign, * represented as a {@code char[]} array. * * <TABLE CLASS=JDBriefTable> * <TR> <TH>Primitive Type</TH> <TH>Integer as ASCII {@code char[]} array</TH></TR> * <TR> <TD>{@code byte}</TD> <TD>{@code '2', '5', '6'}</TD></TR> * <TR> <TD>{@code short}</TD> <TD>{@code '6', '5', '5', '3', '6'}</TD></TR> * * <TR> <TD>{@code int}</TD> * <TD>{@code '2', '1', '4', '7,' '4', '8', '3', '6', '4', '8'}</TD> * </TR> * * <TR> <TD>{@code long}</TD> * <TD>{@code '2', '1', '4', '9', '2', '2', '3', '3', '7', '2', '0', '3', '6', '8', '5', * '4', '7', '7', '5', '8', '0', '8'}</TD> * </TR> * </TABLE> * * @return {@code TRUE} If the input {@code String} is both an integer, and also one which * falls in the range comprised by the specified Java Primitive Type. Return {@code FALSE} * otherwise. * * <BR /><BR /><B>NOTE:</B> The primary purpose of this method is to avoid having to write * {@code try {} catch (NumberFormatException)} code-blocks. Furthermore, if only a check * is desired, and the {@code String} does not actually need to be converted to a number, * this is also more efficient than actually performing the conversion. * * @see #isInteger(String) * @see #isInt(String) * @see #isByte(String) * @see #isLong(String) * @see #isShort(String) */ protected static boolean isOfPrimitiveType(String s, char[] minArr) { int length = s.length(); // Zero length string's are not valid integers. if (length == 0) return false; // A negative integer may begin with a minus-sign. boolean negative = s.charAt(0) == '-'; // **************************************************************************************** // If the string is too short or too long, this method doesn't need to do any work. // We either know the answer immediately (too long), or we can call the simpler method // (in the case that it is too short) // **************************************************************************************** // If a string is shorter than (for type 'int', for example): 2147483647 (10 chars) // then we ought use the simplified method which just checks if the string is an integer. if (length < minArr.length) return isInteger(s); // If the string is longer than (for type 'int', for example): -2147483648 (11 chars) // then it cannot be an integer that fits into primitive 'int', so return false. if (length > (minArr.length + 1)) return false; // If the String is *EXACTLY* 11 characters long (for primitive-type 'int', for example), // but doesn't begin with a negative sign, we also know the answer immediately. if ((!negative) && (length == (minArr.length + 1))) return false; // If the String *EXACTLY* the length of MAX_NUUMBER, but it begins with a negative sign, // we can call the simplified method, instead as well. if (negative && (length == minArr.length)) return isInteger(s); // The **REST** of the code is only executed if the numeric part of the String // (Specifically: leaving out the '-' negative sign, which may or may not be present) // ... if the numeric part of the String is precisely the length of MAX_VALUE / MAX_NUMBER // as determined by the length of the array 'minArr'... If the input string is // **PRECISELY** that length, then the string must be checked in the loop below. int i = negative ? 1 : 0; int j = 0; boolean guaranteedFitIfInteger = false; char c = 0; while (i < length) { c = s.charAt(i); if (! guaranteedFitIfInteger) { if (c > minArr[j]) return false; if (c < minArr[j]) guaranteedFitIfInteger = true; } if (c < '0') return false; if (c > '9') return false; i++; j++; } // THE COMMENT BELOW DELINEATES WHAT HAPPENS FOR THE INPUT-CASE OF PRIMITIVE-TYPE 'INT' // (2147483648)... But it generalizes for byte, short, and long as well. // This might seem very strange. Since the MIN_VALUE ends with an '8', but the // MAX_VALUE ends with a '7', and since we are checking each character to see that // it falls within the array above, **RATHER THAN** just returning TRUE right here, // we have to catch the **LONE** border/edge case where some joker actually passed the // String 2147483648 - which must return FALSE, since the last positive integer is // 2147483647 (see that it has an ending of '7', rather than an '8'). return guaranteedFitIfInteger || negative || (c != minArr[minArr.length-1]); } private static final String Digits = "(\\p{Digit}+)"; private static final String HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. private static final String Exp = "[eE][+-]?"+Digits; /** * A Predicate which uses a regular-expression for checking whether a {@code String} is a valid * & parseable {@code double}, which is guaranteed not to throw a * {@code NumberFormatException} when using the parser {@code Double.parseDouble}. * * <BR /><BR /><SPAN CLASS=CopiedJDK>The Following Description is Directly Copied From: * {@code java.lang.Double.valueOf(String)}, <B>JDK 1.8</B></SPAN> * * <EMBED CLASS='external-html' DATA-FILE-ID=STRP_D_VALUEOF> * * @see #floatingPointPred * @see #isDouble(String) */ public static final Pattern FLOATING_POINT_REGEX = Pattern.compile( // NOTE: Digits, HexDigits & Exp defined ABOVE "[\\x00-\\x20]*"+ // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" string "Infinity|" + // "Infinity" string // A decimal floating-point string representing a finite positive // number without a leading sign has at most five basic pieces: // Digits . Digits ExponentPart FloatTypeSuffix // // Since this method allows integer-only strings as input // in addition to strings of floating-point literals, the // two sub-patterns below are simplifications of the grammar // productions from section 3.10.2 of // The Java Language Specification. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ // . Digits ExponentPart_opt FloatTypeSuffix_opt "(\\.("+Digits+")("+Exp+")?)|"+ // Hexadecimal strings "((" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "(\\.)?)|" + // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*" // Optional trailing "whitespace"; ); /** * This is the floating-point regular-expression, simply converted to a predicate. * @see #FLOATING_POINT_REGEX * @see #isDouble(String) */ public static final Predicate<String> floatingPointPred = FLOATING_POINT_REGEX.asPredicate(); /** * Tests whether an input-{@code String} can be parsed into a {@code double}, without throwing * an exception. * * @return {@code TRUE} <I>if and only if</I> calling {@code Double.valueOf(s)} (or * {@code Double.parseDouble(s)}) is guaranteed to produce a result, without throwing a * {@code NumberFormatException}. * * <BR /><BR /><B STYLE='color: red;'>NOTE:</B> Whenever analyzing performance and * optimizations, it is important to know just "how costly" (as an order of magnitude) a * certain operation really is. Constructors, for instance, that don't allocated much memory * can be two orders of magnitude <I>less costly than</I> the JRE's costs for creating the * {@code StackTrace} object when an exception (such as {@code NumberFormatException}) is * thrown. * * <BR /><BR />Though it costs "extra" to check whether a {@code String} can be parsed by the * Double-String Parser, if the programmer expects that exceptions will occasionally occur, the * amount of time saved by checking a {@code String} before parsing it as a Double-String will * actually save time - <I>even if only 1 in 500 of those {@code String's} are invalid and * would throw the exception, causing a {@code StackTrace} constructor to be invoked.</I> * * @see #FLOATING_POINT_REGEX * @see #floatingPointPred */ public static boolean isDouble(String s) { return floatingPointPred.test(s); } } |