/usr/include/d/4.8/std/string.d is in libphobos-4.8-dev 4.8.2-19ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 | // Written in the D programming language.
/**
String handling functions. Objects of types $(D _string), $(D
wstring), and $(D dstring) are value types and cannot be mutated
element-by-element. For using mutation during building strings, use
$(D char[]), $(D wchar[]), or $(D dchar[]). The $(D *_string) types
are preferable because they don't exhibit undesired aliasing, thus
making code more robust.
Macros: WIKI = Phobos/StdString
Copyright: Copyright Digital Mars 2007-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu),
and Jonathan M Davis
Source: $(PHOBOSSRC std/_string.d)
*/
module std.string;
//debug=string; // uncomment to turn on debugging printf's
debug(string) import core.stdc.stdio;
import core.exception : RangeError, onRangeError;
import core.vararg, core.stdc.stdlib, core.stdc.string,
std.algorithm, std.ascii, std.conv, std.exception, std.format, std.functional,
std.range, std.traits,
std.typecons, std.typetuple, std.uni, std.utf;
//Remove when repeat is finally removed. They're only here as part of the
//deprecation of these functions in std.string.
public import std.algorithm : startsWith, endsWith, cmp, count;
public import std.array : join, split;
version(Windows) extern (C)
{
size_t wcslen(in wchar *);
int wcscmp(in wchar *, in wchar *);
}
version(unittest) import std.algorithm : filter;
/* ************* Exceptions *************** */
/++
Exception thrown on errors in std.string functions.
+/
class StringException : Exception
{
/++
Params:
msg = The message for the exception.
file = The file where the exception occurred.
line = The line number where the exception occurred.
next = The previous exception in the chain of exceptions, if any.
+/
this(string msg,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null) @safe pure nothrow
{
super(msg, file, line, next);
}
}
/++
Compares two ranges of characters lexicographically. The comparison is
case insensitive. Use $(XREF algorithm, cmp) for a case sensitive
comparison. For details see $(XREF uni, icmp).
$(BOOKTABLE,
$(TR $(TD $(D < 0)) $(TD $(D s1 < s2) ))
$(TR $(TD $(D = 0)) $(TD $(D s1 == s2)))
$(TR $(TD $(D > 0)) $(TD $(D s1 > s2)))
)
+/
alias icmp = std.uni.icmp;
unittest
{
debug(string) printf("string.icmp.unittest\n");
assertCTFEable!(
{
assert(icmp("Ü", "ü") == 0, "Über failure");
assert(icmp("abc", "abc") == 0);
assert(icmp("ABC", "abc") == 0);
assert(icmp("abc"w, "abc") == 0);
assert(icmp("ABC", "abc"w) == 0);
assert(icmp("abc"d, "abc") == 0);
assert(icmp("ABC", "abc"d) == 0);
assert(icmp(cast(char[])"abc", "abc") == 0);
assert(icmp("ABC", cast(char[])"abc") == 0);
assert(icmp(cast(wchar[])"abc"w, "abc") == 0);
assert(icmp("ABC", cast(wchar[])"abc"w) == 0);
assert(icmp(cast(dchar[])"abc"d, "abc") == 0);
assert(icmp("ABC", cast(dchar[])"abc"d) == 0);
assert(icmp(cast(string)null, cast(string)null) == 0);
assert(icmp("", "") == 0);
assert(icmp("abc", "abcd") < 0);
assert(icmp("abcd", "abc") > 0);
assert(icmp("abc", "abd") < 0);
assert(icmp("bbc", "abc") > 0);
assert(icmp("abc", "abc"w) == 0);
assert(icmp("ABC"w, "abc") == 0);
assert(icmp("", ""w) == 0);
assert(icmp("abc"w, "abcd") < 0);
assert(icmp("abcd", "abc"w) > 0);
assert(icmp("abc", "abd") < 0);
assert(icmp("bbc"w, "abc") > 0);
assert(icmp("aaa", "aaaa"d) < 0);
assert(icmp("aaaa"w, "aaa"d) > 0);
assert(icmp("aaa"d, "aaa"w) == 0);
assert(icmp("\u0430\u0411\u0543"d, "\u0430\u0411\u0543") == 0);
assert(icmp("\u0430\u0411\u0543"d, "\u0431\u0410\u0544") < 0);
assert(icmp("\u0431\u0411\u0544"d, "\u0431\u0410\u0543") > 0);
assert(icmp("\u0430\u0410\u0543"d, "\u0430\u0410\u0544") < 0);
assert(icmp("\u0430\u0411\u0543"d, "\u0430\u0411\u0543\u0237") < 0);
assert(icmp("\u0430\u0411\u0543\u0237"d, "\u0430\u0411\u0543") > 0);
assert(icmp("aaa", filter!"true"("aaa")) == 0);
assert(icmp(filter!"true"("aaa"), "aaa") == 0);
assert(icmp(filter!"true"("aaa"), filter!"true"("aaa")) == 0);
assert(icmp(filter!"true"("\u0430\u0411\u0543"d), "\u0430\u0411\u0543") == 0);
assert(icmp(filter!"true"("\u0430\u0411\u0543"d), "\u0431\u0410\u0544"w) < 0);
assert(icmp("\u0431\u0411\u0544"d, filter!"true"("\u0431\u0410\u0543"w)) > 0);
assert(icmp("\u0430\u0410\u0543"d, filter!"true"("\u0430\u0410\u0544")) < 0);
assert(icmp(filter!"true"("\u0430\u0411\u0543"d), filter!"true"("\u0430\u0411\u0543\u0237")) < 0);
assert(icmp(filter!"true"("\u0430\u0411\u0543\u0237"d), filter!"true"("\u0430\u0411\u0543")) > 0);
});
}
/++
Returns a C-style zero-terminated string equivalent to $(D s). $(D s)
must not contain embedded $(D '\0')'s as any C function will treat the first
$(D '\0') that it sees as the end of the string. If $(D s.empty) is
$(D true), then a string containing only $(D '\0') is returned.
$(RED Important Note:) When passing a $(D char*) to a C function, and the C
function keeps it around for any reason, make sure that you keep a reference
to it in your D code. Otherwise, it may go away during a garbage collection
cycle and cause a nasty bug when the C code tries to use it.
+/
immutable(char)* toStringz(const(char)[] s) pure nothrow
in
{
// The assert below contradicts the unittests!
//assert(memchr(s.ptr, 0, s.length) == null,
//text(s.length, ": `", s, "'"));
}
out (result)
{
if (result)
{
auto slen = s.length;
while (slen > 0 && s[slen-1] == 0) --slen;
assert(strlen(result) == slen);
assert(memcmp(result, s.ptr, slen) == 0);
}
}
body
{
/+ Unfortunately, this isn't reliable.
We could make this work if string literals are put
in read-only memory and we test if s[] is pointing into
that.
/* Peek past end of s[], if it's 0, no conversion necessary.
* Note that the compiler will put a 0 past the end of static
* strings, and the storage allocator will put a 0 past the end
* of newly allocated char[]'s.
*/
char* p = &s[0] + s.length;
if (*p == 0)
return s;
+/
// Need to make a copy
auto copy = new char[s.length + 1];
copy[0..s.length] = s[];
copy[s.length] = 0;
return assumeUnique(copy).ptr;
}
/++ Ditto +/
immutable(char)* toStringz(string s) pure nothrow
{
if (s.empty) return "".ptr;
/* Peek past end of s[], if it's 0, no conversion necessary.
* Note that the compiler will put a 0 past the end of static
* strings, and the storage allocator will put a 0 past the end
* of newly allocated char[]'s.
*/
immutable p = s.ptr + s.length;
// Is p dereferenceable? A simple test: if the p points to an
// address multiple of 4, then conservatively assume the pointer
// might be pointing to a new block of memory, which might be
// unreadable. Otherwise, it's definitely pointing to valid
// memory.
if ((cast(size_t) p & 3) && *p == 0)
return s.ptr;
return toStringz(cast(const char[]) s);
}
unittest
{
debug(string) printf("string.toStringz.unittest\n");
// TODO: CTFEable toStringz is really necessary?
//assertCTFEable!(
//{
auto p = toStringz("foo");
assert(strlen(p) == 3);
const(char)[] foo = "abbzxyzzy";
p = toStringz(foo[3..5]);
assert(strlen(p) == 2);
string test = "";
p = toStringz(test);
assert(*p == 0);
test = "\0";
p = toStringz(test);
assert(*p == 0);
test = "foo\0";
p = toStringz(test);
assert(p[0] == 'f' && p[1] == 'o' && p[2] == 'o' && p[3] == 0);
//});
}
/**
Flag indicating whether a search is case-sensitive.
*/
enum CaseSensitive { no, yes }
/++
Returns the index of the first occurence of $(D c) in $(D s). If $(D c)
is not found, then $(D -1) is returned.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t indexOf(Char)(in Char[] s,
dchar c,
CaseSensitive cs = CaseSensitive.yes) @safe pure
if (isSomeChar!Char)
{
if (cs == CaseSensitive.yes)
{
static if (Char.sizeof == 1)
{
if (std.ascii.isASCII(c) && !__ctfe)
{ // Plain old ASCII
auto trustedmemchr() @trusted { return cast(Char*)memchr(s.ptr, c, s.length); }
auto p = trustedmemchr();
if (p)
return p - s.ptr;
else
return -1;
}
}
// c is a universal character
foreach (ptrdiff_t i, dchar c2; s)
{
if (c == c2)
return i;
}
}
else
{
if (std.ascii.isASCII(c))
{ // Plain old ASCII
auto c1 = cast(char) std.ascii.toLower(c);
foreach (ptrdiff_t i, c2; s)
{
auto c3 = std.ascii.toLower(c2);
if (c1 == c3)
return i;
}
}
else
{ // c is a universal character
auto c1 = std.uni.toLower(c);
foreach (ptrdiff_t i, dchar c2; s)
{
auto c3 = std.uni.toLower(c2);
if (c1 == c3)
return i;
}
}
}
return -1;
}
unittest
{
debug(string) printf("string.indexOf.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(string, wstring, dstring))
{
assert(indexOf(cast(S)null, cast(dchar)'a') == -1);
assert(indexOf(to!S("def"), cast(dchar)'a') == -1);
assert(indexOf(to!S("abba"), cast(dchar)'a') == 0);
assert(indexOf(to!S("def"), cast(dchar)'f') == 2);
assert(indexOf(to!S("def"), cast(dchar)'a', CaseSensitive.no) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', CaseSensitive.no) == -1);
assert(indexOf(to!S("Abba"), cast(dchar)'a', CaseSensitive.no) == 0);
assert(indexOf(to!S("def"), cast(dchar)'F', CaseSensitive.no) == 2);
assert(indexOf(to!S("ödef"), 'ö', CaseSensitive.no) == 0);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
assert(indexOf("def", cast(char)'f', CaseSensitive.no) == 2);
assert(indexOf(sPlts, cast(char)'P', CaseSensitive.no) == 23);
assert(indexOf(sPlts, cast(char)'R', CaseSensitive.no) == 2);
}
foreach (cs; EnumMembers!CaseSensitive)
{
assert(indexOf("hello\U00010143\u0100\U00010143", '\u0100', cs) == 9);
assert(indexOf("hello\U00010143\u0100\U00010143"w, '\u0100', cs) == 7);
assert(indexOf("hello\U00010143\u0100\U00010143"d, '\u0100', cs) == 6);
}
});
}
/++
Returns the index of the first occurence of $(D c) in $(D s) with respect
to the start index $(D startIdx). If $(D c) is not found, then $(D -1) is
returned. If $(D c) is found the value of the returned index is at least
$(D startIdx). $(D startIdx) represents a codeunit index in $(D s). If the
sequence starting at $(D startIdx) does not represent a well formed codepoint,
then a $(XREF utf,UTFException) may be thrown.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t indexOf(Char)(const(Char)[] s, dchar c, const size_t startIdx,
CaseSensitive cs = CaseSensitive.yes) @safe pure
if (isSomeChar!Char)
{
if (startIdx < s.length)
{
ptrdiff_t foundIdx = indexOf(s[startIdx .. $], c, cs);
if (foundIdx != -1)
{
return foundIdx + cast(ptrdiff_t)startIdx;
}
}
return -1;
}
unittest
{
debug(string) printf("string.indexOf(startIdx).unittest\n");
foreach (S; TypeTuple!(string, wstring, dstring))
{
assert(indexOf(cast(S)null, cast(dchar)'a', 1) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', 1) == -1);
assert(indexOf(to!S("abba"), cast(dchar)'a', 1) == 3);
assert(indexOf(to!S("def"), cast(dchar)'f', 1) == 2);
assert((to!S("def")).indexOf(cast(dchar)'a', 1,
CaseSensitive.no) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', 1,
CaseSensitive.no) == -1);
assert(indexOf(to!S("def"), cast(dchar)'a', 12,
CaseSensitive.no) == -1);
assert(indexOf(to!S("AbbA"), cast(dchar)'a', 2,
CaseSensitive.no) == 3);
assert(indexOf(to!S("def"), cast(dchar)'F', 2, CaseSensitive.no) == 2);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
assert(indexOf("def", cast(char)'f', cast(uint)2,
CaseSensitive.no) == 2);
assert(indexOf(sPlts, cast(char)'P', 12, CaseSensitive.no) == 23);
assert(indexOf(sPlts, cast(char)'R', cast(ulong)1,
CaseSensitive.no) == 2);
}
foreach(cs; EnumMembers!CaseSensitive)
{
assert(indexOf("hello\U00010143\u0100\U00010143", '\u0100', 2, cs)
== 9);
assert(indexOf("hello\U00010143\u0100\U00010143"w, '\u0100', 3, cs)
== 7);
assert(indexOf("hello\U00010143\u0100\U00010143"d, '\u0100', 6, cs)
== 6);
}
}
/++
Returns the index of the first occurence of $(D sub) in $(D s). If $(D sub)
is not found, then $(D -1) is returned.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t indexOf(Char1, Char2)(const(Char1)[] s,
const(Char2)[] sub,
CaseSensitive cs = CaseSensitive.yes)
if (isSomeChar!Char1 && isSomeChar!Char2)
{
const(Char1)[] balance;
if (cs == CaseSensitive.yes)
{
balance = std.algorithm.find(s, sub);
}
else
{
balance = std.algorithm.find!
((a, b) => std.uni.toLower(a) == std.uni.toLower(b))
(s, sub);
}
return balance.empty ? -1 : balance.ptr - s.ptr;
}
unittest
{
debug(string) printf("string.indexOf.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(string, wstring, dstring))
{
foreach (T; TypeTuple!(string, wstring, dstring))
{
assert(indexOf(cast(S)null, to!T("a")) == -1);
assert(indexOf(to!S("def"), to!T("a")) == -1);
assert(indexOf(to!S("abba"), to!T("a")) == 0);
assert(indexOf(to!S("def"), to!T("f")) == 2);
assert(indexOf(to!S("dfefffg"), to!T("fff")) == 3);
assert(indexOf(to!S("dfeffgfff"), to!T("fff")) == 6);
assert(indexOf(to!S("dfeffgfff"), to!T("a"), CaseSensitive.no) == -1);
assert(indexOf(to!S("def"), to!T("a"), CaseSensitive.no) == -1);
assert(indexOf(to!S("abba"), to!T("a"), CaseSensitive.no) == 0);
assert(indexOf(to!S("def"), to!T("f"), CaseSensitive.no) == 2);
assert(indexOf(to!S("dfefffg"), to!T("fff"), CaseSensitive.no) == 3);
assert(indexOf(to!S("dfeffgfff"), to!T("fff"), CaseSensitive.no) == 6);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
S sMars = "Who\'s \'My Favorite Maritian?\'";
assert(indexOf(sMars, to!T("MY fAVe"), CaseSensitive.no) == -1);
assert(indexOf(sMars, to!T("mY fAVOriTe"), CaseSensitive.no) == 7);
assert(indexOf(sPlts, to!T("mArS:"), CaseSensitive.no) == 0);
assert(indexOf(sPlts, to!T("rOcK"), CaseSensitive.no) == 17);
assert(indexOf(sPlts, to!T("Un."), CaseSensitive.no) == 41);
assert(indexOf(sPlts, to!T(sPlts), CaseSensitive.no) == 0);
assert(indexOf("\u0100", to!T("\u0100"), CaseSensitive.no) == 0);
// Thanks to Carlos Santander B. and zwang
assert(indexOf("sus mejores cortesanos. Se embarcaron en el puerto de Dubai y",
to!T("page-break-before"), CaseSensitive.no) == -1);
}
foreach (cs; EnumMembers!CaseSensitive)
{
assert(indexOf("hello\U00010143\u0100\U00010143", to!S("\u0100"), cs) == 9);
assert(indexOf("hello\U00010143\u0100\U00010143"w, to!S("\u0100"), cs) == 7);
assert(indexOf("hello\U00010143\u0100\U00010143"d, to!S("\u0100"), cs) == 6);
}
}
});
}
/++
Returns the index of the first occurence of $(D sub) in $(D s) with
respect to the start index $(D startIdx). If $(D sub) is not found, then
$(D -1) is returned. If $(D sub) is found the value of the returned index
is at least $(D startIdx). $(D startIdx) represents a codeunit index in
$(D s). If the sequence starting at $(D startIdx) does not represent a well
formed codepoint, then a $(XREF utf,UTFException) may be thrown.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t indexOf(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub,
const size_t startIdx, CaseSensitive cs = CaseSensitive.yes)
if (isSomeChar!Char1 && isSomeChar!Char2)
{
if (startIdx < s.length)
{
ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub, cs);
if (foundIdx != -1)
{
return foundIdx + cast(ptrdiff_t)startIdx;
}
}
return -1;
}
unittest
{
debug(string) printf("string.indexOf(startIdx).unittest\n");
foreach(S; TypeTuple!(string, wstring, dstring))
{
foreach(T; TypeTuple!(string, wstring, dstring))
{
assert(indexOf(cast(S)null, to!T("a"), 1337) == -1);
assert(indexOf(to!S("def"), to!T("a"), 0) == -1);
assert(indexOf(to!S("abba"), to!T("a"), 2) == 3);
assert(indexOf(to!S("def"), to!T("f"), 1) == 2);
assert(indexOf(to!S("dfefffg"), to!T("fff"), 1) == 3);
assert(indexOf(to!S("dfeffgfff"), to!T("fff"), 5) == 6);
assert(indexOf(to!S("dfeffgfff"), to!T("a"), 1, CaseSensitive.no) == -1);
assert(indexOf(to!S("def"), to!T("a"), 2, CaseSensitive.no) == -1);
assert(indexOf(to!S("abba"), to!T("a"), 3, CaseSensitive.no) == 3);
assert(indexOf(to!S("def"), to!T("f"), 1, CaseSensitive.no) == 2);
assert(indexOf(to!S("dfefffg"), to!T("fff"), 2, CaseSensitive.no) == 3);
assert(indexOf(to!S("dfeffgfff"), to!T("fff"), 4, CaseSensitive.no) == 6);
assert(indexOf(to!S("dfeffgffföä"), to!T("öä"), 9, CaseSensitive.no) == 9,
to!string(indexOf(to!S("dfeffgffföä"), to!T("öä"), 9, CaseSensitive.no))
~ " " ~ S.stringof ~ " " ~ T.stringof);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
S sMars = "Who\'s \'My Favorite Maritian?\'";
assert(indexOf(sMars, to!T("MY fAVe"), 10,
CaseSensitive.no) == -1);
assert(indexOf(sMars, to!T("mY fAVOriTe"), 4, CaseSensitive.no) == 7);
assert(indexOf(sPlts, to!T("mArS:"), 0, CaseSensitive.no) == 0);
assert(indexOf(sPlts, to!T("rOcK"), 12, CaseSensitive.no) == 17);
assert(indexOf(sPlts, to!T("Un."), 32, CaseSensitive.no) == 41);
assert(indexOf(sPlts, to!T(sPlts), 0, CaseSensitive.no) == 0);
assert(indexOf("\u0100", to!T("\u0100"), 0, CaseSensitive.no) == 0);
// Thanks to Carlos Santander B. and zwang
assert(indexOf("sus mejores cortesanos. Se embarcaron en el puerto de Dubai y",
to!T("page-break-before"), 10, CaseSensitive.no) == -1);
// In order for indexOf with and without index to be consistent
assert(indexOf(to!S(""), to!T("")) == indexOf(to!S(""), to!T(""), 0));
}
foreach(cs; EnumMembers!CaseSensitive)
{
assert(indexOf("hello\U00010143\u0100\U00010143", to!S("\u0100"),
3, cs) == 9);
assert(indexOf("hello\U00010143\u0100\U00010143"w, to!S("\u0100"),
3, cs) == 7);
assert(indexOf("hello\U00010143\u0100\U00010143"d, to!S("\u0100"),
3, cs) == 6);
}
}
}
/++
Returns the index of the last occurence of $(D c) in $(D s). If $(D c)
is not found, then $(D -1) is returned.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t lastIndexOf(Char)(const(Char)[] s,
dchar c,
CaseSensitive cs = CaseSensitive.yes)
if (isSomeChar!Char)
{
if (cs == CaseSensitive.yes)
{
if (std.ascii.isASCII(c))
{
foreach_reverse (i, it; s)
{
if (it == c)
{
return i;
}
}
}
else
{
foreach_reverse (i, dchar it; s)
{
if (it == c)
{
return i;
}
}
}
}
else
{
if (std.ascii.isASCII(c))
{
immutable c1 = std.ascii.toLower(c);
foreach_reverse (i, it; s)
{
immutable c2 = std.ascii.toLower(it);
if (c1 == c2)
{
return i;
}
}
}
else
{
immutable c1 = std.uni.toLower(c);
foreach_reverse (i, dchar it; s)
{
immutable c2 = std.uni.toLower(it);
if (c1 == c2)
{
return i;
}
}
}
}
return -1;
}
unittest
{
debug(string) printf("string.lastIndexOf.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(string, wstring, dstring))
{
assert(lastIndexOf(cast(S) null, 'a') == -1);
assert(lastIndexOf(to!S("def"), 'a') == -1);
assert(lastIndexOf(to!S("abba"), 'a') == 3);
assert(lastIndexOf(to!S("def"), 'f') == 2);
assert(lastIndexOf(to!S("ödef"), 'ö') == 0);
assert(lastIndexOf(cast(S) null, 'a', CaseSensitive.no) == -1);
assert(lastIndexOf(to!S("def"), 'a', CaseSensitive.no) == -1);
assert(lastIndexOf(to!S("AbbA"), 'a', CaseSensitive.no) == 3);
assert(lastIndexOf(to!S("def"), 'F', CaseSensitive.no) == 2);
assert(lastIndexOf(to!S("ödef"), 'ö', CaseSensitive.no) == 0);
assert(lastIndexOf(to!S("i\u0100def"), to!dchar("\u0100"),
CaseSensitive.no) == 1);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
assert(lastIndexOf(to!S("def"), 'f', CaseSensitive.no) == 2);
assert(lastIndexOf(sPlts, 'M', CaseSensitive.no) == 34);
assert(lastIndexOf(sPlts, 'S', CaseSensitive.no) == 40);
}
foreach (cs; EnumMembers!CaseSensitive)
{
assert(lastIndexOf("\U00010143\u0100\U00010143hello", '\u0100', cs) == 4);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"w, '\u0100', cs) == 2);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"d, '\u0100', cs) == 1);
}
});
}
/++
Returns the index of the last occurence of $(D c) in $(D s). If $(D c) is
not found, then $(D -1) is returned. The $(D startIdx) slices $(D s) in
the following way $(D s[0 .. startIdx]). $(D startIdx) represents a
codeunit index in $(D s). If the sequence ending at $(D startIdx) does not
represent a well formed codepoint, then a $(XREF utf,UTFException) may be
thrown.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t lastIndexOf(Char)(const(Char)[] s, dchar c, const size_t startIdx,
CaseSensitive cs = CaseSensitive.yes)
if (isSomeChar!Char)
{
if (startIdx <= s.length)
{
return lastIndexOf(s[0u .. startIdx], c, cs);
}
return -1;
}
unittest
{
debug(string) printf("string.lastIndexOf.unittest\n");
foreach(S; TypeTuple!(string, wstring, dstring))
{
assert(lastIndexOf(cast(S) null, 'a') == -1);
assert(lastIndexOf(to!S("def"), 'a') == -1);
assert(lastIndexOf(to!S("abba"), 'a', 3) == 0);
assert(lastIndexOf(to!S("deff"), 'f', 3) == 2);
assert(lastIndexOf(cast(S) null, 'a', CaseSensitive.no) == -1);
assert(lastIndexOf(to!S("def"), 'a', CaseSensitive.no) == -1);
assert(lastIndexOf(to!S("AbbAa"), 'a', to!ushort(4), CaseSensitive.no) == 3,
to!string(lastIndexOf(to!S("AbbAa"), 'a', 4, CaseSensitive.no)));
assert(lastIndexOf(to!S("def"), 'F', 3, CaseSensitive.no) == 2);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
assert(lastIndexOf(to!S("def"), 'f', 4, CaseSensitive.no) == -1);
assert(lastIndexOf(sPlts, 'M', sPlts.length -2, CaseSensitive.no) == 34);
assert(lastIndexOf(sPlts, 'S', sPlts.length -2, CaseSensitive.no) == 40);
}
foreach(cs; EnumMembers!CaseSensitive)
{
assert(lastIndexOf("\U00010143\u0100\U00010143hello", '\u0100', cs) == 4);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"w, '\u0100', cs) == 2);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"d, '\u0100', cs) == 1);
}
}
/++
Returns the index of the last occurence of $(D sub) in $(D s). If $(D sub)
is not found, then $(D -1) is returned.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t lastIndexOf(Char1, Char2)(const(Char1)[] s,
const(Char2)[] sub,
CaseSensitive cs = CaseSensitive.yes)
if (isSomeChar!Char1 && isSomeChar!Char2)
{
if (sub.empty)
return s.length;
if (walkLength(sub) == 1)
return lastIndexOf(s, sub.front, cs);
if (cs == CaseSensitive.yes)
{
static if (is(Unqual!Char1 == Unqual!Char2))
{
immutable c = sub[0];
for (ptrdiff_t i = s.length - sub.length; i >= 0; --i)
{
if (s[i] == c)
{
if (__ctfe)
{
foreach (j; 1 .. sub.length)
{
if (s[i + j] != sub[j])
continue;
}
return i;
}
else
{
if (memcmp(&s[i + 1], &sub[1], sub.length - 1) == 0)
return i;
}
}
}
}
else
{
for (size_t i = s.length; !s.empty;)
{
if (s.endsWith(sub))
return cast(ptrdiff_t)i - to!(const(Char1)[])(sub).length;
i -= strideBack(s, i);
s = s[0 .. i];
}
}
}
else
{
for (size_t i = s.length; !s.empty;)
{
if (endsWith!((a, b) => std.uni.toLower(a) == std.uni.toLower(b))
(s, sub))
{
return cast(ptrdiff_t)i - to!(const(Char1)[])(sub).length;
}
i -= strideBack(s, i);
s = s[0 .. i];
}
}
return -1;
}
unittest
{
debug(string) printf("string.lastIndexOf.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(string, wstring, dstring))
{
foreach (T; TypeTuple!(string, wstring, dstring))
{
enum typeStr = S.stringof ~ " " ~ T.stringof;
assert(lastIndexOf(cast(S)null, to!T("a")) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("c")) == 6, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("cd")) == 6, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("ef")) == 8, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("c")) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("cd")) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("x")) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("xy")) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("")) == 10, typeStr);
assert(lastIndexOf(to!S("öabcdefcdef"), to!T("ö")) == 0, typeStr);
assert(lastIndexOf(cast(S)null, to!T("a"), CaseSensitive.no) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("c"), CaseSensitive.no) == 6, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("cD"), CaseSensitive.no) == 6, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("x"), CaseSensitive.no) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("xy"), CaseSensitive.no) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T(""), CaseSensitive.no) == 10, typeStr);
assert(lastIndexOf(to!S("öabcdefcdef"), to!T("ö"), CaseSensitive.no) == 0, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("c"), CaseSensitive.no) == 6, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("cd"), CaseSensitive.no) == 6, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("def"), CaseSensitive.no) == 7, typeStr);
assert(lastIndexOf(to!S("ödfeffgfff"), to!T("ö"), CaseSensitive.yes) == 0);
S sPlts = "Mars: the fourth Rock (Planet) from the Sun.";
S sMars = "Who\'s \'My Favorite Maritian?\'";
assert(lastIndexOf(sMars, to!T("RiTE maR"), CaseSensitive.no) == 14, typeStr);
assert(lastIndexOf(sPlts, to!T("FOuRTh"), CaseSensitive.no) == 10, typeStr);
assert(lastIndexOf(sMars, to!T("whO\'s \'MY"), CaseSensitive.no) == 0, typeStr);
assert(lastIndexOf(sMars, to!T(sMars), CaseSensitive.no) == 0, typeStr);
}
foreach (cs; EnumMembers!CaseSensitive)
{
enum csString = to!string(cs);
assert(lastIndexOf("\U00010143\u0100\U00010143hello", to!S("\u0100"), cs) == 4, csString);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"w, to!S("\u0100"), cs) == 2, csString);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"d, to!S("\u0100"), cs) == 1, csString);
}
}
});
}
/++
Returns the index of the last occurence of $(D sub) in $(D s). If $(D sub)
is not found, then $(D -1) is returned. The $(D startIdx) slices $(D s) in
the following way $(D s[0 .. startIdx]). $(D startIdx) represents a
codeunit index in $(D s). If the sequence ending at $(D startIdx) does not
represent a well formed codepoint, then a $(XREF utf,UTFException) may be
thrown.
$(D cs) indicates whether the comparisons are case sensitive.
+/
ptrdiff_t lastIndexOf(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub,
const size_t startIdx, CaseSensitive cs = CaseSensitive.yes)
if (isSomeChar!Char1 && isSomeChar!Char2)
{
if (startIdx <= s.length)
{
return lastIndexOf(s[0u .. startIdx], sub, cs);
}
return -1;
}
unittest
{
debug(string) printf("string.lastIndexOf.unittest\n");
foreach(S; TypeTuple!(string, wstring, dstring))
{
foreach(T; TypeTuple!(string, wstring, dstring))
{
enum typeStr = S.stringof ~ " " ~ T.stringof;
assert(lastIndexOf(cast(S)null, to!T("a")) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("c"), 5) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("cd"), 3) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("ef"), 6) == 4, typeStr ~
format(" %u", lastIndexOf(to!S("abcdefcdef"), to!T("ef"), 6)));
assert(lastIndexOf(to!S("abcdefCdef"), to!T("c"), 5) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("cd"), 3) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdefx"), to!T("x"), 1) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdefxy"), to!T("xy"), 6) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T(""), 8) == 8, typeStr);
assert(lastIndexOf(to!S("öafö"), to!T("ö"), 3) == 0, typeStr ~
to!string(lastIndexOf(to!S("öafö"), to!T("ö"), 3))); //BUG 10472
assert(lastIndexOf(cast(S)null, to!T("a"), 1, CaseSensitive.no) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("c"), 5, CaseSensitive.no) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefCdef"), to!T("cD"), 4, CaseSensitive.no) == 2, typeStr ~
" " ~ to!string(lastIndexOf(to!S("abcdefCdef"), to!T("cD"), 3, CaseSensitive.no)));
assert(lastIndexOf(to!S("abcdefcdef"), to!T("x"),3 , CaseSensitive.no) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdefXY"), to!T("xy"), 4, CaseSensitive.no) == -1, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T(""), 7, CaseSensitive.no) == 7, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("c"), 4, CaseSensitive.no) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("cd"), 4, CaseSensitive.no) == 2, typeStr);
assert(lastIndexOf(to!S("abcdefcdef"), to!T("def"), 6, CaseSensitive.no) == 3, typeStr);
assert(lastIndexOf(to!S(""), to!T(""), 0) == lastIndexOf(to!S(""), to!T("")), typeStr);
}
foreach(cs; EnumMembers!CaseSensitive)
{
enum csString = to!string(cs);
assert(lastIndexOf("\U00010143\u0100\U00010143hello", to!S("\u0100"), 6, cs) == 4, csString);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"w, to!S("\u0100"), 6, cs) == 2, csString);
assert(lastIndexOf("\U00010143\u0100\U00010143hello"d, to!S("\u0100"), 3, cs) == 1, csString);
}
}
}
/**
* Returns the representation of a string, which has the same type
* as the string except the character type is replaced by $(D ubyte),
* $(D ushort), or $(D uint) depending on the character width.
*/
auto representation(Char)(Char[] s) pure nothrow
if (isSomeChar!Char)
{
// Get representation type
alias TypeTuple!(ubyte, ushort, uint)[Char.sizeof / 2] U;
// const and immutable storage classes
static if (is(Char == immutable))
alias T = immutable(U);
else static if (is(Char == const))
alias T = const(U);
else
alias T = U;
// shared storage class (because shared(const(T)) is possible)
static if (is(Char == shared))
alias ST = shared(T);
else
alias ST = T;
return cast(ST[]) s;
}
///
unittest
{
string s = "hello";
static assert(is(typeof(representation(s)) == immutable(ubyte)[]));
assert(representation(s) is cast(immutable(ubyte)[]) s);
assert(representation(s) == [0x68, 0x65, 0x6c, 0x6c, 0x6f]);
}
unittest
{
assertCTFEable!(
{
void test(Char, T)(Char[] str)
{
static assert(is(typeof(representation(str)) == T[]));
assert(representation(str) is cast(T[]) str);
}
foreach (Type; TypeTuple!(Tuple!(char , ubyte ),
Tuple!(wchar, ushort),
Tuple!(dchar, uint )))
{
alias Char = FieldTypeTuple!Type[0];
alias Int = FieldTypeTuple!Type[1];
enum immutable(Char)[] hello = "hello";
test!( immutable Char, immutable Int)(hello);
test!( const Char, const Int)(hello);
test!( Char, Int)(hello.dup);
test!( shared Char, shared Int)(cast(shared) hello.dup);
test!(const shared Char, const shared Int)(hello);
}
});
}
/++
Returns a string which is identical to $(D s) except that all of its
characters are converted to lowercase (by preforming Unicode lowercase mapping).
If none of $(D s) characters were affected, then $(D s) itself is returned.
+/
alias toLower = std.uni.toLower;
/++
Converts $(D s) to lowercase (by performing Unicode lowercase mapping) in place.
For a few characters string length may increase after the transformation,
in such a case the function reallocates exactly once.
If $(D s) does not have any uppercase characters, then $(D s) is unaltered.
+/
alias toLowerInPlace = std.uni.toLowerInPlace;
/++
Returns a string which is identical to $(D s) except that all of its
characters are converted to uppercase (by preforming Unicode uppercase mapping).
If none of $(D s) characters were affected, then $(D s) itself is returned.
+/
alias toUpper = std.uni.toUpper;
/++
Converts $(D s) to uppercase (by performing Unicode uppercase mapping) in place.
For a few characters string length may increase after the transformation,
in such a case the function reallocates exactly once.
If $(D s) does not have any lowercase characters, then $(D s) is unaltered.
+/
alias toUpperInPlace = std.uni.toUpperInPlace;
/++
Capitalize the first character of $(D s) and convert the rest of $(D s)
to lowercase.
+/
S capitalize(S)(S s) @trusted pure
if (isSomeString!S)
{
Unqual!(typeof(s[0]))[] retval;
bool changed = false;
foreach (i, dchar c; s)
{
dchar c2;
if (i == 0)
{
c2 = std.uni.toUpper(c);
if (c != c2)
changed = true;
}
else
{
c2 = std.uni.toLower(c);
if (c != c2)
{
if (!changed)
{
changed = true;
retval = s[0 .. i].dup;
}
}
}
if (changed)
std.utf.encode(retval, c2);
}
return changed ? cast(S)retval : s;
}
unittest
{
assertCTFEable!(
{
foreach (S; TypeTuple!(string, wstring, dstring, char[], wchar[], dchar[]))
{
S s1 = to!S("FoL");
S s2;
s2 = capitalize(s1);
assert(cmp(s2, "Fol") == 0);
assert(s2 !is s1);
s2 = capitalize(s1[0 .. 2]);
assert(cmp(s2, "Fo") == 0);
assert(s2.ptr == s1.ptr);
s1 = to!S("fOl");
s2 = capitalize(s1);
assert(cmp(s2, "Fol") == 0);
assert(s2 !is s1);
s1 = to!S("\u0131 \u0130");
s2 = capitalize(s1);
assert(cmp(s2, "I \u0130") == 0);
assert(s2 !is s1);
s1 = to!S("\u017F \u0049");
s2 = capitalize(s1);
assert(cmp(s2, "\u0053 \u0069") == 0);
assert(s2 !is s1);
}
});
}
/++
Split $(D s) into an array of lines using $(D '\r'), $(D '\n'),
$(D "\r\n"), $(XREF uni, lineSep), and $(XREF uni, paraSep) as delimiters.
If $(D keepTerm) is set to $(D KeepTerminator.yes), then the delimiter
is included in the strings returned.
+/
enum KeepTerminator : bool { no, yes }
/// ditto
S[] splitLines(S)(S s, KeepTerminator keepTerm = KeepTerminator.no) @safe pure
if (isSomeString!S)
{
size_t iStart = 0;
size_t nextI = 0;
auto retval = appender!(S[])();
for (size_t i; i < s.length; i = nextI)
{
immutable c = decode(s, nextI);
if (c == '\r' || c == '\n' || c == lineSep || c == paraSep)
{
immutable isWinEOL = c == '\r' && i + 1 < s.length && s[i + 1] == '\n';
auto iEnd = i;
if (keepTerm == KeepTerminator.yes)
{
iEnd = isWinEOL? nextI + 1 : nextI;
}
retval.put(s[iStart .. iEnd]);
iStart = nextI;
if (isWinEOL)
{
++nextI;
++iStart;
}
}
}
if (iStart != nextI)
retval.put(s[iStart .. $]);
return retval.data;
}
unittest
{
debug(string) printf("string.splitLines.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
auto s = to!S("\rpeter\n\rpaul\r\njerry\u2028ice\u2029cream\n\nsunday\n");
auto lines = splitLines(s);
assert(lines.length == 9);
assert(lines[0] == "");
assert(lines[1] == "peter");
assert(lines[2] == "");
assert(lines[3] == "paul");
assert(lines[4] == "jerry");
assert(lines[5] == "ice");
assert(lines[6] == "cream");
assert(lines[7] == "");
assert(lines[8] == "sunday");
lines = splitLines(s, KeepTerminator.yes);
assert(lines.length == 9);
assert(lines[0] == "\r");
assert(lines[1] == "peter\n");
assert(lines[2] == "\r");
assert(lines[3] == "paul\r\n");
assert(lines[4] == "jerry\u2028");
assert(lines[5] == "ice\u2029");
assert(lines[6] == "cream\n");
assert(lines[7] == "\n");
assert(lines[8] == "sunday\n");
s.popBack(); // Lop-off trailing \n
lines = splitLines(s);
assert(lines.length == 9);
assert(lines[8] == "sunday");
lines = splitLines(s, KeepTerminator.yes);
assert(lines.length == 9);
assert(lines[8] == "sunday");
}
});
}
/++
Strips leading whitespace.
+/
C[] stripLeft(C)(C[] str) @safe pure
if (isSomeChar!C)
{
foreach (i, dchar c; str)
{
if (!std.uni.isWhite(c))
return str[i .. $];
}
return str[$ .. $]; //Empty string with correct type.
}
///
@safe pure unittest
{
assert(stripLeft(" hello world ") ==
"hello world ");
assert(stripLeft("\n\t\v\rhello world\n\t\v\r") ==
"hello world\n\t\v\r");
assert(stripLeft("hello world") ==
"hello world");
assert(stripLeft([lineSep] ~ "hello world" ~ lineSep) ==
"hello world" ~ [lineSep]);
assert(stripLeft([paraSep] ~ "hello world" ~ paraSep) ==
"hello world" ~ [paraSep]);
}
/++
Strips trailing whitespace.
+/
C[] stripRight(C)(C[] str) @safe pure
if (isSomeChar!C)
{
foreach_reverse (i, dchar c; str)
{
if (!std.uni.isWhite(c))
return str[0 .. i + codeLength!C(c)];
}
return str[0 .. 0];
}
///
@safe pure unittest
{
assert(stripRight(" hello world ") ==
" hello world");
assert(stripRight("\n\t\v\rhello world\n\t\v\r") ==
"\n\t\v\rhello world");
assert(stripRight("hello world") ==
"hello world");
assert(stripRight([lineSep] ~ "hello world" ~ lineSep) ==
[lineSep] ~ "hello world");
assert(stripRight([paraSep] ~ "hello world" ~ paraSep) ==
[paraSep] ~ "hello world");
}
/++
Strips both leading and trailing whitespace.
+/
C[] strip(C)(C[] str) @safe pure
if (isSomeChar!C)
{
return stripRight(stripLeft(str));
}
///
@safe pure unittest
{
assert(strip(" hello world ") ==
"hello world");
assert(strip("\n\t\v\rhello world\n\t\v\r") ==
"hello world");
assert(strip("hello world") ==
"hello world");
assert(strip([lineSep] ~ "hello world" ~ [lineSep]) ==
"hello world");
assert(strip([paraSep] ~ "hello world" ~ [paraSep]) ==
"hello world");
}
unittest
{
debug(string) printf("string.strip.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!( char[], const char[], string,
wchar[], const wchar[], wstring,
dchar[], const dchar[], dstring))
{
assert(equal(stripLeft(to!S(" foo\t ")), "foo\t "));
assert(equal(stripLeft(to!S("\u2008 foo\t \u2007")), "foo\t \u2007"));
assert(equal(stripLeft(to!S("\u0085 μ \u0085 \u00BB \r")), "μ \u0085 \u00BB \r"));
assert(equal(stripLeft(to!S("1")), "1"));
assert(equal(stripLeft(to!S("\U0010FFFE")), "\U0010FFFE"));
assert(equal(stripLeft(to!S("")), ""));
assert(equal(stripRight(to!S(" foo\t ")), " foo"));
assert(equal(stripRight(to!S("\u2008 foo\t \u2007")), "\u2008 foo"));
assert(equal(stripRight(to!S("\u0085 μ \u0085 \u00BB \r")), "\u0085 μ \u0085 \u00BB"));
assert(equal(stripRight(to!S("1")), "1"));
assert(equal(stripRight(to!S("\U0010FFFE")), "\U0010FFFE"));
assert(equal(stripRight(to!S("")), ""));
assert(equal(strip(to!S(" foo\t ")), "foo"));
assert(equal(strip(to!S("\u2008 foo\t \u2007")), "foo"));
assert(equal(strip(to!S("\u0085 μ \u0085 \u00BB \r")), "μ \u0085 \u00BB"));
assert(equal(strip(to!S("\U0010FFFE")), "\U0010FFFE"));
assert(equal(strip(to!S("")), ""));
}
});
}
@safe pure unittest
{
assertCTFEable!(
{
wstring s = " ";
assert(s.sameTail(s.stripLeft()));
assert(s.sameHead(s.stripRight()));
});
}
/++
If $(D str) ends with $(D delimiter), then $(D str) is returned without
$(D delimiter) on its end. If it $(D str) does $(I not) end with
$(D delimiter), then it is returned unchanged.
If no $(D delimiter) is given, then one trailing $(D '\r'), $(D '\n'),
$(D "\r\n"), $(XREF uni, lineSep), or $(XREF uni, paraSep) is removed from
the end of $(D str). If $(D str) does not end with any of those characters,
then it is returned unchanged.
+/
C[] chomp(C)(C[] str) @safe pure
if (isSomeChar!C)
{
if (str.empty)
return str;
switch (str[$ - 1])
{
case '\n':
{
if (str.length > 1 && str[$ - 2] == '\r')
return str[0 .. $ - 2];
goto case;
}
case '\r':
return str[0 .. $ - 1];
//Pops off the last character if it's lineSep or paraSep.
static if (is(C : const char))
{
//In UTF-8, lineSep and paraSep are [226, 128, 168], and
//[226, 128, 169] respectively, so their first two bytes are the same.
case 168: //Last byte of lineSep
case 169: //Last byte of paraSep
{
if (str.length > 2 && str[$ - 2] == 128 && str[$ - 3] == 226)
return str [0 .. $ - 3];
goto default;
}
}
else
{
case lineSep:
case paraSep:
return str[0 .. $ - 1];
}
default:
return str;
}
}
/// Ditto
C1[] chomp(C1, C2)(C1[] str, const(C2)[] delimiter) @safe pure
if (isSomeChar!C1 && isSomeChar!C2)
{
if (delimiter.empty)
return chomp(str);
static if (is(Unqual!C1 == Unqual!C2))
{
if (str.endsWith(delimiter))
return str[0 .. $ - delimiter.length];
}
auto orig = str;
foreach_reverse (dchar c; delimiter)
{
if (str.empty || str.back != c)
return orig;
str.popBack();
}
return str;
}
///
@safe pure unittest
{
assert(chomp(" hello world \n\r") == " hello world \n");
assert(chomp(" hello world \r\n") == " hello world ");
assert(chomp(" hello world \n\n") == " hello world \n");
assert(chomp(" hello world \n\n ") == " hello world \n\n ");
assert(chomp(" hello world \n\n" ~ [lineSep]) == " hello world \n\n");
assert(chomp(" hello world \n\n" ~ [paraSep]) == " hello world \n\n");
assert(chomp(" hello world") == " hello world");
assert(chomp("") == "");
assert(chomp(" hello world", "orld") == " hello w");
assert(chomp(" hello world", " he") == " hello world");
assert(chomp("", "hello") == "");
}
unittest
{
debug(string) printf("string.chomp.unittest\n");
string s;
assertCTFEable!(
{
foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
// @@@ BUG IN COMPILER, MUST INSERT CAST
assert(chomp(cast(S)null) is null);
assert(chomp(to!S("hello")) == "hello");
assert(chomp(to!S("hello\n")) == "hello");
assert(chomp(to!S("hello\r")) == "hello");
assert(chomp(to!S("hello\r\n")) == "hello");
assert(chomp(to!S("hello\n\r")) == "hello\n");
assert(chomp(to!S("hello\n\n")) == "hello\n");
assert(chomp(to!S("hello\r\r")) == "hello\r");
assert(chomp(to!S("hello\nxxx\n")) == "hello\nxxx");
assert(chomp(to!S("hello\u2028")) == "hello");
assert(chomp(to!S("hello\u2029")) == "hello");
assert(chomp(to!S("hello\u2028\u2028")) == "hello\u2028");
assert(chomp(to!S("hello\u2029\u2029")) == "hello\u2029");
foreach (T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
// @@@ BUG IN COMPILER, MUST INSERT CAST
assert(chomp(cast(S)null, cast(T)null) is null);
assert(chomp(to!S("hello\n"), cast(T)null) == "hello");
assert(chomp(to!S("hello"), to!T("o")) == "hell");
assert(chomp(to!S("hello"), to!T("p")) == "hello");
// @@@ BUG IN COMPILER, MUST INSERT CAST
assert(chomp(to!S("hello"), cast(T) null) == "hello");
assert(chomp(to!S("hello"), to!T("llo")) == "he");
assert(chomp(to!S("\uFF28ello"), to!T("llo")) == "\uFF28e");
assert(chomp(to!S("\uFF28el\uFF4co"), to!T("l\uFF4co")) == "\uFF28e");
}
}
});
}
/++
If $(D str) starts with $(D delimiter), then the part of $(D str) following
$(D delimiter) is returned. If it $(D str) does $(I not) start with
$(D delimiter), then it is returned unchanged.
+/
C1[] chompPrefix(C1, C2)(C1[] str, C2[] delimiter) @safe pure
if (isSomeChar!C1 && isSomeChar!C2)
{
static if (is(Unqual!C1 == Unqual!C2))
{
if (str.startsWith(delimiter))
return str[delimiter.length .. $];
return str;
}
else
{
auto orig = str;
size_t index = 0;
foreach (dchar c; delimiter)
{
if (index >= str.length || decode(str, index) != c)
return orig;
}
return str[index .. $];
}
}
///
@safe pure unittest
{
assert(chompPrefix("hello world", "he") == "llo world");
assert(chompPrefix("hello world", "hello w") == "orld");
assert(chompPrefix("hello world", " world") == "hello world");
assert(chompPrefix("", "hello") == "");
}
/* @safe */ pure unittest
{
assertCTFEable!(
{
foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
foreach (T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
assert(equal(chompPrefix(to!S("abcdefgh"), to!T("abcde")), "fgh"));
assert(equal(chompPrefix(to!S("abcde"), to!T("abcdefgh")), "abcde"));
assert(equal(chompPrefix(to!S("\uFF28el\uFF4co"), to!T("\uFF28el\uFF4co")), ""));
assert(equal(chompPrefix(to!S("\uFF28el\uFF4co"), to!T("\uFF28el")), "\uFF4co"));
assert(equal(chompPrefix(to!S("\uFF28el"), to!T("\uFF28el\uFF4co")), "\uFF28el"));
}
}
});
}
/++
Returns $(D str) without its last character, if there is one. If $(D str)
ends with $(D "\r\n"), then both are removed. If $(D str) is empty, then
then it is returned unchanged.
+/
S chop(S)(S str) @safe pure
if (isSomeString!S)
{
if (str.empty)
return str;
if (str.length >= 2 && str[$ - 1] == '\n' && str[$ - 2] == '\r')
return str[0 .. $ - 2];
str.popBack();
return str;
}
///
@safe pure unittest
{
assert(chop("hello world") == "hello worl");
assert(chop("hello world\n") == "hello world");
assert(chop("hello world\r") == "hello world");
assert(chop("hello world\n\r") == "hello world\n");
assert(chop("hello world\r\n") == "hello world");
assert(chop("Walter Bright") == "Walter Brigh");
assert(chop("") == "");
}
unittest
{
debug(string) printf("string.chop.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
assert(chop(cast(S) null) is null);
assert(equal(chop(to!S("hello")), "hell"));
assert(equal(chop(to!S("hello\r\n")), "hello"));
assert(equal(chop(to!S("hello\n\r")), "hello\n"));
assert(equal(chop(to!S("Verité")), "Verit"));
assert(equal(chop(to!S(`さいごの果実`)), "さいごの果"));
assert(equal(chop(to!S(`ミツバチと科学者`)), "ミツバチと科学"));
}
});
}
/++
Left justify $(D s) in a field $(D width) characters wide. $(D fillChar)
is the character that will be used to fill up the space in the field that
$(D s) doesn't fill.
+/
S leftJustify(S)(S s, size_t width, dchar fillChar = ' ') @trusted pure
if (isSomeString!S)
{
alias typeof(s[0]) C;
if (cast(dchar)(cast(C)fillChar) == fillChar)
{
immutable len = s.walkLength();
if (len >= width)
return s;
auto retval = new Unqual!(C)[width - len + s.length];
retval[0 .. s.length] = s[];
retval[s.length .. $] = cast(C)fillChar;
return cast(S)retval;
}
else
{
auto dstr = to!dstring(s);
if (dstr.length >= width)
return s;
auto retval = new dchar[](width);
retval[0 .. dstr.length] = dstr[];
retval[dstr.length .. $] = fillChar;
return to!S(retval);
}
}
/++
Right justify $(D s) in a field $(D width) characters wide. $(D fillChar)
is the character that will be used to fill up the space in the field that
$(D s) doesn't fill.
+/
S rightJustify(S)(S s, size_t width, dchar fillChar = ' ') @trusted pure
if (isSomeString!S)
{
alias typeof(s[0]) C;
if (cast(dchar)(cast(C)fillChar) == fillChar)
{
immutable len = s.walkLength();
if (len >= width)
return s;
auto retval = new Unqual!C[width - len + s.length];
retval[0 .. $ - s.length] = cast(C)fillChar;
retval[$ - s.length .. $] = s[];
return cast(S)retval;
}
else
{
auto dstr = to!dstring(s);
if (dstr.length >= width)
return s;
auto retval = new dchar[](width);
retval[0 .. $ - dstr.length] = fillChar;
retval[$ - dstr.length .. $] = dstr[];
return to!S(retval);
}
}
/++
Center $(D s) in a field $(D width) characters wide. $(D fillChar)
is the character that will be used to fill up the space in the field that
$(D s) doesn't fill.
+/
S center(S)(S s, size_t width, dchar fillChar = ' ') @trusted pure
if (isSomeString!S)
{
alias typeof(s[0]) C;
if (cast(dchar)(cast(C)fillChar) == fillChar)
{
immutable len = s.walkLength();
if (len >= width)
return s;
auto retval = new Unqual!C[width - len + s.length];
immutable left = (retval.length - s.length) / 2;
retval[0 .. left] = cast(C)fillChar;
retval[left .. left + s.length] = s[];
retval[left + s.length .. $] = cast(C)fillChar;
return to!S(retval);
}
else
{
auto dstr = to!dstring(s);
if (dstr.length >= width)
return s;
auto retval = new dchar[](width);
immutable left = (retval.length - dstr.length) / 2;
retval[0 .. left] = fillChar;
retval[left .. left + dstr.length] = dstr[];
retval[left + dstr.length .. $] = fillChar;
return to!S(retval);
}
}
unittest
{
debug(string) printf("string.justify.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
S s = to!S("hello");
assert(leftJustify(s, 2) == "hello");
assert(rightJustify(s, 2) == "hello");
assert(center(s, 2) == "hello");
assert(leftJustify(s, 7) == "hello ");
assert(rightJustify(s, 7) == " hello");
assert(center(s, 7) == " hello ");
assert(leftJustify(s, 8) == "hello ");
assert(rightJustify(s, 8) == " hello");
assert(center(s, 8) == " hello ");
assert(leftJustify(s, 8, '\u0100') == "hello\u0100\u0100\u0100");
assert(rightJustify(s, 8, '\u0100') == "\u0100\u0100\u0100hello");
assert(center(s, 8, '\u0100') == "\u0100hello\u0100\u0100");
}
});
}
/++
Replace each tab character in $(D s) with the number of spaces necessary
to align the following character at the next tab stop where $(D tabSize)
is the distance between tab stops.
+/
S detab(S)(S s, size_t tabSize = 8) @trusted pure
if (isSomeString!S)
{
assert(tabSize > 0);
alias Unqual!(typeof(s[0])) C;
bool changes = false;
C[] result;
int column;
size_t nspaces;
foreach (size_t i, dchar c; s)
{
switch (c)
{
case '\t':
nspaces = tabSize - (column % tabSize);
if (!changes)
{
changes = true;
result = null;
result.length = s.length + nspaces - 1;
result.length = i + nspaces;
result[0 .. i] = s[0 .. i];
result[i .. i + nspaces] = ' ';
}
else
{
ptrdiff_t j = result.length;
result.length = j + nspaces;
result[j .. j + nspaces] = ' ';
}
column += nspaces;
break;
case '\r':
case '\n':
case paraSep:
case lineSep:
column = 0;
goto L1;
default:
column++;
L1:
if (changes)
{
if (cast(dchar)(cast(C)c) == c)
result ~= cast(C)c;
else
std.utf.encode(result, c);
}
break;
}
}
return changes ? cast(S) result : s;
}
unittest
{
debug(string) printf("string.detab.unittest\n");
assertCTFEable!(
{
foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
{
S s = to!S("This \tis\t a fofof\tof list");
assert(cmp(detab(s), "This is a fofof of list") == 0);
assert(detab(cast(S)null) is null);
assert(detab("").empty);
assert(detab("a") == "a");
assert(detab("\t") == " ");
assert(detab("\t", 3) == " ");
assert(detab("\t", 9) == " ");
assert(detab( " ab\t asdf ") == " ab asdf ");
assert(detab( " \U00010000b\tasdf ") == " \U00010000b asdf ");
}
});
}
/++
Replaces spaces in $(D s) with the optimal number of tabs.
All spaces and tabs at the end of a line are removed.
Params:
s = String to convert.
tabSize = Tab columns are $(D tabSize) spaces apart.
+/
S entab(S)(S s, size_t tabSize = 8) @trusted pure
if (isSomeString!S)
{
bool changes = false;
alias Unqual!(typeof(s[0])) C;
C[] result;
int nspaces = 0;
int nwhite = 0;
size_t column = 0; // column number
foreach (size_t i, dchar c; s)
{
void change()
{
changes = true;
result = null;
result.length = s.length;
result.length = i;
result[0 .. i] = s[0 .. i];
}
switch (c)
{
case '\t':
nwhite++;
if (nspaces)
{
if (!changes)
change();
ptrdiff_t j = result.length - nspaces;
auto ntabs = (((column - nspaces) % tabSize) + nspaces) / tabSize;
result.length = j + ntabs;
result[j .. j + ntabs] = '\t';
nwhite += ntabs - nspaces;
nspaces = 0;
}
column = (column + tabSize) / tabSize * tabSize;
break;
case '\r':
case '\n':
case paraSep:
case lineSep:
// Truncate any trailing spaces or tabs
if (nwhite)
{
if (!changes)
change();
result = result[0 .. result.length - nwhite];
}
break;
default:
if (nspaces >= 2 && (column % tabSize) == 0)
{
if (!changes)
change();
auto j = result.length - nspaces;
auto ntabs = (nspaces + tabSize - 1) / tabSize;
result.length = j + ntabs;
result[j .. j + ntabs] = '\t';
nwhite += ntabs - nspaces;
nspaces = 0;
}
if (c == ' ')
{ nwhite++;
nspaces++;
}
else
{ nwhite = 0;
nspaces = 0;
}
column++;
break;
}
if (changes)
{
if (cast(dchar)(cast(C)c) == c)
result ~= cast(C)c;
else
std.utf.encode(result, c);
}
}
// Truncate any trailing spaces or tabs
if (nwhite)
{
if (changes)
result = result[0 .. result.length - nwhite];
else
s = s[0 .. s.length - nwhite];
}
return changes ? assumeUnique(result) : s;
}
unittest
{
debug(string) printf("string.entab.unittest\n");
assertCTFEable!(
{
assert(entab(cast(string) null) is null);
assert(entab("").empty);
assert(entab("a") == "a");
assert(entab(" ") == "");
assert(entab(" x") == "\tx");
assert(entab(" ab asdf ") == " ab\tasdf");
assert(entab(" ab asdf ") == " ab\t asdf");
assert(entab(" ab \t asdf ") == " ab\t asdf");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\ta");
assert(entab("1234567 \ta") == "1234567\t\t\ta");
assert(entab("a ") == "a");
assert(entab("a\v") == "a\v");
assert(entab("a\f") == "a\f");
assert(entab("a\n") == "a\n");
assert(entab("a\n\r") == "a\n\r");
assert(entab("a\r\n") == "a\r\n");
assert(entab("a\u2028") == "a\u2028");
assert(entab("a\u2029") == "a\u2029");
assert(entab("a ") == "a");
assert(entab("a\t") == "a");
assert(entab("\uFF28\uFF45\uFF4C\uFF4C567 \t\uFF4F \t") ==
"\uFF28\uFF45\uFF4C\uFF4C567\t\t\uFF4F");
});
}
/++
Replaces the characters in $(D str) which are keys in $(D transTable) with
their corresponding values in $(D transTable). $(D transTable) is an AA
where its keys are $(D dchar) and its values are either $(D dchar) or some
type of string. Also, if $(D toRemove) is given, the characters in it are
removed from $(D str) prior to translation. $(D str) itself is unaltered.
A copy with the changes is returned.
See_Also:
$(LREF tr)
$(XREF array, replace)
Params:
str = The original string.
transTable = The AA indicating which characters to replace and what to
replace them with.
toRemove = The characters to remove from the string.
+/
C1[] translate(C1, C2 = immutable char)(C1[] str,
dchar[dchar] transTable,
const(C2)[] toRemove = null) @safe pure
if (isSomeChar!C1 && isSomeChar!C2)
{
auto buffer = appender!(C1[])();
translateImpl(str, transTable, toRemove, buffer);
return buffer.data;
}
///
@safe pure unittest
{
dchar[dchar] transTable1 = ['e' : '5', 'o' : '7', '5': 'q'];
assert(translate("hello world", transTable1) == "h5ll7 w7rld");
assert(translate("hello world", transTable1, "low") == "h5 rd");
string[dchar] transTable2 = ['e' : "5", 'o' : "orange"];
assert(translate("hello world", transTable2) == "h5llorange worangerld");
}
/* @safe */ pure unittest
{
assertCTFEable!(
{
foreach (S; TypeTuple!( char[], const( char)[], immutable( char)[],
wchar[], const(wchar)[], immutable(wchar)[],
dchar[], const(dchar)[], immutable(dchar)[]))
{
assert(translate(to!S("hello world"), cast(dchar[dchar])['h' : 'q', 'l' : '5']) ==
to!S("qe55o wor5d"));
assert(translate(to!S("hello world"), cast(dchar[dchar])['o' : 'l', 'l' : '\U00010143']) ==
to!S("he\U00010143\U00010143l wlr\U00010143d"));
assert(translate(to!S("hello \U00010143 world"), cast(dchar[dchar])['h' : 'q', 'l': '5']) ==
to!S("qe55o \U00010143 wor5d"));
assert(translate(to!S("hello \U00010143 world"), cast(dchar[dchar])['o' : '0', '\U00010143' : 'o']) ==
to!S("hell0 o w0rld"));
assert(translate(to!S("hello world"), cast(dchar[dchar])null) == to!S("hello world"));
foreach (T; TypeTuple!( char[], const( char)[], immutable( char)[],
wchar[], const(wchar)[], immutable(wchar)[],
dchar[], const(dchar)[], immutable(dchar)[]))
{
assert(translate(to!S("hello world"),
cast(dchar[dchar])['h' : 'q', 'l' : '5'],
to!T("r")) ==
to!S("qe55o wo5d"));
assert(translate(to!S("hello world"),
cast(dchar[dchar])['h' : 'q', 'l' : '5'],
to!T("helo")) ==
to!S(" wrd"));
assert(translate(to!S("hello world"),
cast(dchar[dchar])['h' : 'q', 'l' : '5'],
to!T("q5")) ==
to!S("qe55o wor5d"));
assert(translate(to!S("hello \U00010143 world"),
cast(dchar[dchar])['o' : '0', '\U00010143' : 'o'],
to!T("\U00010143 ")) ==
to!S("hell0w0rld"));
}
auto s = to!S("hello world");
dchar[dchar] transTable = ['h' : 'q', 'l' : '5'];
static assert(is(typeof(s) == typeof(translate(s, transTable))));
}
});
}
/++ Ditto +/
C1[] translate(C1, S, C2 = immutable char)(C1[] str,
S[dchar] transTable,
const(C2)[] toRemove = null) @safe pure
if (isSomeChar!C1 && isSomeString!S && isSomeChar!C2)
{
auto buffer = appender!(C1[])();
translateImpl(str, transTable, toRemove, buffer);
return buffer.data;
}
/* @safe */ pure unittest
{
assertCTFEable!(
{
foreach (S; TypeTuple!( char[], const( char)[], immutable( char)[],
wchar[], const(wchar)[], immutable(wchar)[],
dchar[], const(dchar)[], immutable(dchar)[]))
{
assert(translate(to!S("hello world"), ['h' : "yellow", 'l' : "42"]) ==
to!S("yellowe4242o wor42d"));
assert(translate(to!S("hello world"), ['o' : "owl", 'l' : "\U00010143\U00010143"]) ==
to!S("he\U00010143\U00010143\U00010143\U00010143owl wowlr\U00010143\U00010143d"));
assert(translate(to!S("hello \U00010143 world"), ['h' : "yellow", 'l' : "42"]) ==
to!S("yellowe4242o \U00010143 wor42d"));
assert(translate(to!S("hello \U00010143 world"), ['o' : "owl", 'l' : "\U00010143\U00010143"]) ==
to!S("he\U00010143\U00010143\U00010143\U00010143owl \U00010143 wowlr\U00010143\U00010143d"));
assert(translate(to!S("hello \U00010143 world"), ['h' : ""]) ==
to!S("ello \U00010143 world"));
assert(translate(to!S("hello \U00010143 world"), ['\U00010143' : ""]) ==
to!S("hello world"));
assert(translate(to!S("hello world"), cast(string[dchar])null) == to!S("hello world"));
foreach (T; TypeTuple!( char[], const( char)[], immutable( char)[],
wchar[], const(wchar)[], immutable(wchar)[],
dchar[], const(dchar)[], immutable(dchar)[]))
{
assert(translate(to!S("hello world"), ['h' : "yellow", 'l' : "42"], to!T("r")) ==
to!S("yellowe4242o wo42d"));
assert(translate(to!S("hello world"), ['h' : "yellow", 'l' : "42"], to!T("helo")) ==
to!S(" wrd"));
assert(translate(to!S("hello world"), ['h' : "yellow", 'l' : "42"], to!T("y42")) ==
to!S("yellowe4242o wor42d"));
assert(translate(to!S("hello \U00010143 world"),
['o' : "owl", '\U00010143' : "\n"],
to!T("\U00010143 ")) ==
to!S("hellowlwowlrld"));
assert(translate(to!S("hello world"), ['h' : "yellow", 'l' : "42"], to!T("hello world")) ==
to!S(""));
assert(translate(to!S("hello world"), ['h' : "yellow", 'l' : "42"], to!T("42")) ==
to!S("yellowe4242o wor42d"));
}
auto s = to!S("hello world");
string[dchar] transTable = ['h' : "silly", 'l' : "putty"];
static assert(is(typeof(s) == typeof(translate(s, transTable))));
}
});
}
/++
This is an overload of $(D translate) which takes an existing buffer to write the contents to.
Params:
str = The original string.
transTable = The AA indicating which characters to replace and what to
replace them with.
toRemove = The characters to remove from the string.
buffer = An output range to write the contents to.
+/
void translate(C1, C2 = immutable char, Buffer)(C1[] str,
dchar[dchar] transTable,
const(C2)[] toRemove,
Buffer buffer)
if (isSomeChar!C1 && isSomeChar!C2 && isOutputRange!(Buffer, C1))
{
translateImpl(str, transTable, toRemove, buffer);
}
///
@safe pure unittest
{
dchar[dchar] transTable1 = ['e' : '5', 'o' : '7', '5': 'q'];
auto buffer = appender!(dchar[])();
translate("hello world", transTable1, null, buffer);
assert(buffer.data == "h5ll7 w7rld");
buffer.clear();
translate("hello world", transTable1, "low", buffer);
assert(buffer.data == "h5 rd");
buffer.clear();
string[dchar] transTable2 = ['e' : "5", 'o' : "orange"];
translate("hello world", transTable2, null, buffer);
assert(buffer.data == "h5llorange worangerld");
}
/++ Ditto +/
void translate(C1, S, C2 = immutable char, Buffer)(C1[] str,
S[dchar] transTable,
const(C2)[] toRemove,
Buffer buffer)
if (isSomeChar!C1 && isSomeString!S && isSomeChar!C2 && isOutputRange!(Buffer, S))
{
translateImpl(str, transTable, toRemove, buffer);
}
private void translateImpl(C1, T, C2, Buffer)(C1[] str,
T transTable,
const(C2)[] toRemove,
Buffer buffer)
{
bool[dchar] removeTable;
foreach (dchar c; toRemove)
removeTable[c] = true;
foreach (dchar c; str)
{
if (c in removeTable)
continue;
auto newC = c in transTable;
if (newC)
put(buffer, *newC);
else
put(buffer, c);
}
}
/++
This is an $(I $(RED ASCII-only)) overload of $(LREF _translate). It
will $(I not) work with Unicode. It exists as an optimization for the
cases where Unicode processing is not necessary.
Unlike the other overloads of $(LREF _translate), this one does not take
an AA. Rather, it takes a $(D string) generated by $(LREF makeTrans).
The array generated by $(D makeTrans) is $(D 256) elements long such that
the index is equal to the ASCII character being replaced and the value is
equal to the character that it's being replaced with. Note that translate
does not decode any of the characters, so you can actually pass it Extended
ASCII characters if you want to (ASCII only actually uses $(D 128)
characters), but be warned that Extended ASCII characters are not valid
Unicode and therefore will result in a $(D UTFException) being thrown from
most other Phobos functions.
Also, because no decoding occurs, it is possible to use this overload to
translate ASCII characters within a proper UTF-8 string without altering the
other, non-ASCII characters. It's replacing any code unit greater than
$(D 127) with another code unit or replacing any code unit with another code
unit greater than $(D 127) which will cause UTF validation issues.
See_Also:
$(LREF tr)
$(XREF array, replace)
Params:
str = The original string.
transTable = The string indicating which characters to replace and what
to replace them with. It is generated by $(LREF makeTrans).
toRemove = The characters to remove from the string.
+/
C[] translate(C = immutable char)(in char[] str, in char[] transTable, in char[] toRemove = null) @trusted pure nothrow
if (is(Unqual!C == char))
in
{
assert(transTable.length == 256);
}
body
{
bool[256] remTable = false;
foreach (char c; toRemove)
remTable[c] = true;
size_t count = 0;
foreach (char c; str)
{
if (!remTable[c])
++count;
}
auto buffer = new char[count];
translateImplAscii(str, transTable, remTable, buffer, toRemove);
return cast(C[])(buffer);
}
/++ Ditto +/
string makeTrans(in char[] from, in char[] to) @trusted pure nothrow
in
{
assert(from.length == to.length);
assert(from.length <= 256);
foreach (char c; from)
assert(std.ascii.isASCII(c));
foreach (char c; to)
assert(std.ascii.isASCII(c));
}
body
{
char[] transTable = new char[256];
foreach (i; 0 .. transTable.length)
transTable[i] = cast(char)i;
foreach (i; 0 .. from.length)
transTable[from[i]] = to[i];
return assumeUnique(transTable);
}
///
@safe pure nothrow unittest
{
auto transTable1 = makeTrans("eo5", "57q");
assert(translate("hello world", transTable1) == "h5ll7 w7rld");
assert(translate("hello world", transTable1, "low") == "h5 rd");
}
@safe pure unittest
{
assertCTFEable!(
{
foreach (C; TypeTuple!(char, const char, immutable char))
{
assert(translate!C("hello world", makeTrans("hl", "q5")) == to!(C[])("qe55o wor5d"));
auto s = to!(C[])("hello world");
auto transTable = makeTrans("hl", "q5");
static assert(is(typeof(s) == typeof(translate!C(s, transTable))));
}
foreach (S; TypeTuple!(char[], const(char)[], immutable(char)[]))
{
assert(translate(to!S("hello world"), makeTrans("hl", "q5")) == to!S("qe55o wor5d"));
assert(translate(to!S("hello \U00010143 world"), makeTrans("hl", "q5")) ==
to!S("qe55o \U00010143 wor5d"));
assert(translate(to!S("hello world"), makeTrans("ol", "1o")), to!S("heool wlrdd"));
assert(translate(to!S("hello world"), makeTrans("", "")) == to!S("hello world"));
assert(translate(to!S("hello world"), makeTrans("12345", "67890")) == to!S("hello world"));
assert(translate(to!S("hello \U00010143 world"), makeTrans("12345", "67890")) ==
to!S("hello \U00010143 world"));
foreach (T; TypeTuple!(char[], const(char)[], immutable(char)[]))
{
assert(translate(to!S("hello world"), makeTrans("hl", "q5"), to!T("r")) ==
to!S("qe55o wo5d"));
assert(translate(to!S("hello \U00010143 world"), makeTrans("hl", "q5"), to!T("r")) ==
to!S("qe55o \U00010143 wo5d"));
assert(translate(to!S("hello world"), makeTrans("hl", "q5"), to!T("helo")) ==
to!S(" wrd"));
assert(translate(to!S("hello world"), makeTrans("hl", "q5"), to!T("q5")) ==
to!S("qe55o wor5d"));
}
}
});
}
/++
This is an $(I $(RED ASCII-only)) overload of $(D translate) which takes an existing buffer to write the contents to.
Params:
str = The original string.
transTable = The string indicating which characters to replace and what
to replace them with. It is generated by $(LREF makeTrans).
toRemove = The characters to remove from the string.
buffer = An output range to write the contents to.
+/
void translate(C = immutable char, Buffer)(in char[] str, in char[] transTable, in char[] toRemove, Buffer buffer)
if (is(Unqual!C == char) && isOutputRange!(Buffer, char))
in
{
assert(transTable.length == 256);
}
body
{
bool[256] remTable = false;
foreach (char c; toRemove)
remTable[c] = true;
translateImplAscii(str, transTable, remTable, buffer, toRemove);
}
///
@safe pure unittest
{
auto buffer = appender!(char[])();
auto transTable1 = makeTrans("eo5", "57q");
translate("hello world", transTable1, null, buffer);
assert(buffer.data == "h5ll7 w7rld");
buffer.clear();
translate("hello world", transTable1, "low", buffer);
assert(buffer.data == "h5 rd");
}
private void translateImplAscii(C = immutable char, Buffer)(in char[] str, in char[] transTable, ref bool[256] remTable, Buffer buffer, in char[] toRemove = null)
{
static if (isOutputRange!(Buffer, char))
{
foreach (char c; str)
{
if (!remTable[c])
put(buffer, transTable[c]);
}
}
else
{
size_t i = 0;
foreach (char c; str)
{
if (!remTable[c])
buffer[i++] = transTable[c];
}
}
}
/*****************************************************
* Format arguments into a string.
*
* Params: fmt = Format string. For detailed specification, see $(XREF format,formattedWrite).
* args = Variadic list of arguments to format into returned string.
*
* $(RED format's current implementation has been replaced with $(LREF xformat)'s
* implementation. in November 2012.
* This is seamless for most code, but it makes it so that the only
* argument that can be a format string is the first one, so any
* code which used multiple format strings has broken. Please change
* your calls to format accordingly.
*
* e.g.:
* ----
* format("key = %s", key, ", value = %s", value)
* ----
* needs to be rewritten as:
* ----
* format("key = %s, value = %s", key, value)
* ----
* )
*/
string format(Char, Args...)(in Char[] fmt, Args args)
{
auto w = appender!string();
auto n = formattedWrite(w, fmt, args);
version (all)
{
// In the future, this check will be removed to increase consistency
// with formattedWrite
enforce(n == args.length, new FormatException(
text("Orphan format arguments: args[", n, "..", args.length, "]")));
}
return w.data;
}
unittest
{
debug(string) printf("std.string.format.unittest\n");
assertCTFEable!(
{
// assert(format(null) == "");
assert(format("foo") == "foo");
assert(format("foo%%") == "foo%");
assert(format("foo%s", 'C') == "fooC");
assert(format("%s foo", "bar") == "bar foo");
assert(format("%s foo %s", "bar", "abc") == "bar foo abc");
assert(format("foo %d", -123) == "foo -123");
assert(format("foo %d", 123) == "foo 123");
assertThrown!FormatException(format("foo %s"));
assertThrown!FormatException(format("foo %s", 123, 456));
assert(format("hel%slo%s%s%s", "world", -138, 'c', true) ==
"helworldlo-138ctrue");
});
}
/*****************************************************
* Format arguments into buffer <i>buf</i> which must be large
* enough to hold the result. Throws RangeError if it is not.
* Returns: The slice of $(D buf) containing the formatted string.
*
* $(RED sformat's current implementation has been replaced with $(LREF xsformat)'s
* implementation. in November 2012.
* This is seamless for most code, but it makes it so that the only
* argument that can be a format string is the first one, so any
* code which used multiple format strings has broken. Please change
* your calls to sformat accordingly.
*
* e.g.:
* ----
* sformat(buf, "key = %s", key, ", value = %s", value)
* ----
* needs to be rewritten as:
* ----
* sformat(buf, "key = %s, value = %s", key, value)
* ----
* )
*/
char[] sformat(Char, Args...)(char[] buf, in Char[] fmt, Args args)
{
size_t i;
struct Sink
{
void put(dchar c)
{
char[4] enc;
auto n = encode(enc, c);
if (buf.length < i + n)
onRangeError("std.string.sformat", 0);
buf[i .. i + n] = enc[0 .. n];
i += n;
}
void put(const(char)[] s)
{
if (buf.length < i + s.length)
onRangeError("std.string.sformat", 0);
buf[i .. i + s.length] = s[];
i += s.length;
}
void put(const(wchar)[] s)
{
for (; !s.empty; s.popFront())
put(s.front);
}
void put(const(dchar)[] s)
{
for (; !s.empty; s.popFront())
put(s.front);
}
}
auto n = formattedWrite(Sink(), fmt, args);
version (all)
{
// In the future, this check will be removed to increase consistency
// with formattedWrite
enforce(n == args.length, new FormatException(
text("Orphan format arguments: args[", n, "..", args.length, "]")));
}
return buf[0 .. i];
}
unittest
{
debug(string) printf("std.string.sformat.unittest\n");
assertCTFEable!(
{
char[10] buf;
assert(sformat(buf[], "foo") == "foo");
assert(sformat(buf[], "foo%%") == "foo%");
assert(sformat(buf[], "foo%s", 'C') == "fooC");
assert(sformat(buf[], "%s foo", "bar") == "bar foo");
assertThrown!RangeError(sformat(buf[], "%s foo %s", "bar", "abc"));
assert(sformat(buf[], "foo %d", -123) == "foo -123");
assert(sformat(buf[], "foo %d", 123) == "foo 123");
assertThrown!FormatException(sformat(buf[], "foo %s"));
assertThrown!FormatException(sformat(buf[], "foo %s", 123, 456));
assert(sformat(buf[], "%s %s %s", "c"c, "w"w, "d"d) == "c w d");
});
}
/*****************************************************
* $(RED Deprecated. It will be removed in November 2013.
* Please use std.string.format instead.)
*
* Format arguments into a string.
*
* $(LREF format) was changed to use this implementation in November 2012,
*/
deprecated("Please use std.string.format instead.") alias format xformat;
deprecated unittest
{
debug(string) printf("std.string.xformat.unittest\n");
assertCTFEable!(
{
// assert(xformat(null) == "");
assert(xformat("foo") == "foo");
assert(xformat("foo%%") == "foo%");
assert(xformat("foo%s", 'C') == "fooC");
assert(xformat("%s foo", "bar") == "bar foo");
assert(xformat("%s foo %s", "bar", "abc") == "bar foo abc");
assert(xformat("foo %d", -123) == "foo -123");
assert(xformat("foo %d", 123) == "foo 123");
assertThrown!FormatException(xformat("foo %s"));
assertThrown!FormatException(xformat("foo %s", 123, 456));
});
}
/*****************************************************
* $(RED Deprecated. It will be removed in November 2013.
* Please use std.string.sformat instead.)
*
* Format arguments into string $(D buf) which must be large
* enough to hold the result. Throws RangeError if it is not.
*
* $(LREF sformat) was changed to use this implementation in November 2012,
*/
deprecated("Please use std.string.sformat instead.") alias sformat xsformat;
deprecated unittest
{
debug(string) printf("std.string.xsformat.unittest\n");
assertCTFEable!(
{
char[10] buf;
assert(xsformat(buf[], "foo") == "foo");
assert(xsformat(buf[], "foo%%") == "foo%");
assert(xsformat(buf[], "foo%s", 'C') == "fooC");
assert(xsformat(buf[], "%s foo", "bar") == "bar foo");
assertThrown!RangeError(xsformat(buf[], "%s foo %s", "bar", "abc"));
assert(xsformat(buf[], "foo %d", -123) == "foo -123");
assert(xsformat(buf[], "foo %d", 123) == "foo 123");
assertThrown!FormatException(xsformat(buf[], "foo %s"));
assertThrown!FormatException(xsformat(buf[], "foo %s", 123, 456));
assert(xsformat(buf[], "%s %s %s", "c"c, "w"w, "d"d) == "c w d");
});
}
/***********************************************
* See if character c is in the pattern.
* Patterns:
*
* A <i>pattern</i> is an array of characters much like a <i>character
* class</i> in regular expressions. A sequence of characters
* can be given, such as "abcde". The '-' can represent a range
* of characters, as "a-e" represents the same pattern as "abcde".
* "a-fA-F0-9" represents all the hex characters.
* If the first character of a pattern is '^', then the pattern
* is negated, i.e. "^0-9" means any character except a digit.
* The functions inPattern, <b>countchars</b>, <b>removeschars</b>,
* and <b>squeeze</b>
* use patterns.
*
* Note: In the future, the pattern syntax may be improved
* to be more like regular expression character classes.
*/
bool inPattern(S)(dchar c, in S pattern) @safe pure if (isSomeString!S)
{
bool result = false;
int range = 0;
dchar lastc;
foreach (size_t i, dchar p; pattern)
{
if (p == '^' && i == 0)
{
result = true;
if (i + 1 == pattern.length)
return (c == p); // or should this be an error?
}
else if (range)
{
range = 0;
if (lastc <= c && c <= p || c == p)
return !result;
}
else if (p == '-' && i > result && i + 1 < pattern.length)
{
range = 1;
continue;
}
else if (c == p)
return !result;
lastc = p;
}
return result;
}
unittest
{
debug(string) printf("std.string.inPattern.unittest\n");
assertCTFEable!(
{
assert(inPattern('x', "x") == 1);
assert(inPattern('x', "y") == 0);
assert(inPattern('x', string.init) == 0);
assert(inPattern('x', "^y") == 1);
assert(inPattern('x', "yxxy") == 1);
assert(inPattern('x', "^yxxy") == 0);
assert(inPattern('x', "^abcd") == 1);
assert(inPattern('^', "^^") == 0);
assert(inPattern('^', "^") == 1);
assert(inPattern('^', "a^") == 1);
assert(inPattern('x', "a-z") == 1);
assert(inPattern('x', "A-Z") == 0);
assert(inPattern('x', "^a-z") == 0);
assert(inPattern('x', "^A-Z") == 1);
assert(inPattern('-', "a-") == 1);
assert(inPattern('-', "^A-") == 0);
assert(inPattern('a', "z-a") == 1);
assert(inPattern('z', "z-a") == 1);
assert(inPattern('x', "z-a") == 0);
});
}
/***********************************************
* See if character c is in the intersection of the patterns.
*/
bool inPattern(S)(dchar c, S[] patterns) @safe pure if (isSomeString!S)
{
foreach (string pattern; patterns)
{
if (!inPattern(c, pattern))
{
return false;
}
}
return true;
}
/********************************************
* Count characters in s that match pattern.
*/
size_t countchars(S, S1)(S s, in S1 pattern) @safe pure if (isSomeString!S && isSomeString!S1)
{
size_t count;
foreach (dchar c; s)
{
count += inPattern(c, pattern);
}
return count;
}
unittest
{
debug(string) printf("std.string.count.unittest\n");
assertCTFEable!(
{
assert(countchars("abc", "a-c") == 3);
assert(countchars("hello world", "or") == 3);
});
}
/********************************************
* Return string that is s with all characters removed that match pattern.
*/
S removechars(S)(S s, in S pattern) @safe pure if (isSomeString!S)
{
Unqual!(typeof(s[0]))[] r;
bool changed = false;
foreach (size_t i, dchar c; s)
{
if (inPattern(c, pattern))
{
if (!changed)
{
changed = true;
r = s[0 .. i].dup;
}
continue;
}
if (changed)
{
std.utf.encode(r, c);
}
}
if (changed)
return r;
else
return s;
}
unittest
{
debug(string) printf("std.string.removechars.unittest\n");
assertCTFEable!(
{
assert(removechars("abc", "a-c").length == 0);
assert(removechars("hello world", "or") == "hell wld");
assert(removechars("hello world", "d") == "hello worl");
assert(removechars("hah", "h") == "a");
});
}
/***************************************************
* Return string where sequences of a character in s[] from pattern[]
* are replaced with a single instance of that character.
* If pattern is null, it defaults to all characters.
*/
S squeeze(S)(S s, in S pattern = null)
{
Unqual!(typeof(s[0]))[] r;
dchar lastc;
size_t lasti;
int run;
bool changed;
foreach (size_t i, dchar c; s)
{
if (run && lastc == c)
{
changed = true;
}
else if (pattern is null || inPattern(c, pattern))
{
run = 1;
if (changed)
{
if (r is null)
r = s[0 .. lasti].dup;
std.utf.encode(r, c);
}
else
lasti = i + std.utf.stride(s, i);
lastc = c;
}
else
{
run = 0;
if (changed)
{
if (r is null)
r = s[0 .. lasti].dup;
std.utf.encode(r, c);
}
}
}
return changed ? ((r is null) ? s[0 .. lasti] : cast(S) r) : s;
}
unittest
{
debug(string) printf("std.string.squeeze.unittest\n");
assertCTFEable!(
{
string s;
assert(squeeze("hello") == "helo");
s = "abcd";
assert(squeeze(s) is s);
s = "xyzz";
assert(squeeze(s).ptr == s.ptr); // should just be a slice
assert(squeeze("hello goodbyee", "oe") == "hello godbye");
});
}
/***************************************************************
Finds the position $(D_PARAM pos) of the first character in $(D_PARAM
s) that does not match $(D_PARAM pattern) (in the terminology used by
$(LINK2 std_string.html,inPattern)). Updates $(D_PARAM s =
s[pos..$]). Returns the slice from the beginning of the original
(before update) string up to, and excluding, $(D_PARAM pos).
Example:
---
string s = "123abc";
string t = munch(s, "0123456789");
assert(t == "123" && s == "abc");
t = munch(s, "0123456789");
assert(t == "" && s == "abc");
---
The $(D_PARAM munch) function is mostly convenient for skipping
certain category of characters (e.g. whitespace) when parsing
strings. (In such cases, the return value is not used.)
*/
S1 munch(S1, S2)(ref S1 s, S2 pattern)
{
size_t j = s.length;
foreach (i, c; s)
{
if (!inPattern(c, pattern))
{
j = i;
break;
}
}
scope(exit) s = s[j .. $];
return s[0 .. j];
}
@safe pure unittest
{
string s = "123abc";
string t = munch(s, "0123456789");
assert(t == "123" && s == "abc");
t = munch(s, "0123456789");
assert(t == "" && s == "abc");
}
/**********************************************
* Return string that is the 'successor' to s[].
* If the rightmost character is a-zA-Z0-9, it is incremented within
* its case or digits. If it generates a carry, the process is
* repeated with the one to its immediate left.
*/
S succ(S)(S s) @safe pure if (isSomeString!S)
{
if (s.length && std.ascii.isAlphaNum(s[$ - 1]))
{
auto r = s.dup;
size_t i = r.length - 1;
while (1)
{
dchar c = s[i];
dchar carry;
switch (c)
{
case '9':
c = '0';
carry = '1';
goto Lcarry;
case 'z':
case 'Z':
c -= 'Z' - 'A';
carry = c;
Lcarry:
r[i] = cast(char)c;
if (i == 0)
{
auto t = new typeof(r[0])[r.length + 1];
t[0] = cast(char) carry;
t[1 .. $] = r[];
return t;
}
i--;
break;
default:
if (std.ascii.isAlphaNum(c))
r[i]++;
return r;
}
}
}
return s;
}
unittest
{
debug(string) printf("std.string.succ.unittest\n");
assertCTFEable!(
{
assert(succ(string.init) is null);
assert(succ("!@#$%") == "!@#$%");
assert(succ("1") == "2");
assert(succ("9") == "10");
assert(succ("999") == "1000");
assert(succ("zz99") == "aaa00");
});
}
/++
Replaces the characters in $(D str) which are in $(D from) with the
the corresponding characters in $(D to) and returns the resulting string.
$(D tr) is based on
$(WEB pubs.opengroup.org/onlinepubs/9699919799/utilities/_tr.html, Posix's tr),
though it doesn't do everything that the Posix utility does.
Params:
str = The original string.
from = The characters to replace.
to = The characters to replace with.
modifiers = String containing modifiers.
Modifiers:
$(BOOKTABLE,
$(TR $(TD Modifier) $(TD Description))
$(TR $(TD $(D 'c')) $(TD Complement the list of characters in $(D from)))
$(TR $(TD $(D 'd')) $(TD Removes matching characters with no corresponding
replacement in $(D to)))
$(TR $(TD $(D 's')) $(TD Removes adjacent duplicates in the replaced
characters))
)
If the modifier $(D 'd') is present, then the number of characters in
$(D to) may be only $(D 0) or $(D 1).
If the modifier $(D 'd') is $(I not) present, and $(D to) is empty, then
$(D to) is taken to be the same as $(D from).
If the modifier $(D 'd') is $(I not) present, and $(D to) is shorter than
$(D from), then $(D to) is extended by replicating the last charcter in
$(D to).
Both $(D from) and $(D to) may contain ranges using the $(D '-') character
(e.g. $(D "a-d") is synonymous with $(D "abcd").) Neither accept a leading
$(D '^') as meaning the complement of the string (use the $(D 'c') modifier
for that).
+/
C1[] tr(C1, C2, C3, C4 = immutable char)
(C1[] str, const(C2)[] from, const(C3)[] to, const(C4)[] modifiers = null)
{
bool mod_c;
bool mod_d;
bool mod_s;
foreach (char c; modifiers)
{
switch (c)
{
case 'c': mod_c = 1; break; // complement
case 'd': mod_d = 1; break; // delete unreplaced chars
case 's': mod_s = 1; break; // squeeze duplicated replaced chars
default: assert(0);
}
}
if (to.empty && !mod_d)
to = std.conv.to!(typeof(to))(from);
auto result = appender!(C1[])();
bool modified;
dchar lastc;
foreach (dchar c; str)
{
dchar lastf;
dchar lastt;
dchar newc;
int n = 0;
for (size_t i = 0; i < from.length; )
{
dchar f = std.utf.decode(from, i);
if (f == '-' && lastf != dchar.init && i < from.length)
{
dchar nextf = std.utf.decode(from, i);
if (lastf <= c && c <= nextf)
{
n += c - lastf - 1;
if (mod_c)
goto Lnotfound;
goto Lfound;
}
n += nextf - lastf;
lastf = lastf.init;
continue;
}
if (c == f)
{ if (mod_c)
goto Lnotfound;
goto Lfound;
}
lastf = f;
n++;
}
if (!mod_c)
goto Lnotfound;
n = 0; // consider it 'found' at position 0
Lfound:
// Find the nth character in to[]
dchar nextt;
for (size_t i = 0; i < to.length; )
{ dchar t = std.utf.decode(to, i);
if (t == '-' && lastt != dchar.init && i < to.length)
{
nextt = std.utf.decode(to, i);
n -= nextt - lastt;
if (n < 0)
{
newc = nextt + n + 1;
goto Lnewc;
}
lastt = dchar.init;
continue;
}
if (n == 0)
{ newc = t;
goto Lnewc;
}
lastt = t;
nextt = t;
n--;
}
if (mod_d)
continue;
newc = nextt;
Lnewc:
if (mod_s && modified && newc == lastc)
continue;
result.put(newc);
assert(newc != dchar.init);
modified = true;
lastc = newc;
continue;
Lnotfound:
result.put(c);
lastc = c;
modified = false;
}
return result.data;
}
unittest
{
debug(string) printf("std.string.tr.unittest\n");
import std.algorithm;
// Complete list of test types; too slow to test'em all
// alias TestTypes = TypeTuple!(
// char[], const( char)[], immutable( char)[],
// wchar[], const(wchar)[], immutable(wchar)[],
// dchar[], const(dchar)[], immutable(dchar)[]);
// Reduced list of test types
alias TestTypes = TypeTuple!(char[], const(wchar)[], immutable(dchar)[]);
assertCTFEable!(
{
foreach (S; TestTypes)
{
foreach (T; TestTypes)
{
foreach (U; TestTypes)
{
assert(equal(tr(to!S("abcdef"), to!T("cd"), to!U("CD")), "abCDef"));
assert(equal(tr(to!S("abcdef"), to!T("b-d"), to!U("B-D")), "aBCDef"));
assert(equal(tr(to!S("abcdefgh"), to!T("b-dh"), to!U("B-Dx")), "aBCDefgx"));
assert(equal(tr(to!S("abcdefgh"), to!T("b-dh"), to!U("B-CDx")), "aBCDefgx"));
assert(equal(tr(to!S("abcdefgh"), to!T("b-dh"), to!U("B-BCDx")), "aBCDefgx"));
assert(equal(tr(to!S("abcdef"), to!T("ef"), to!U("*"), to!S("c")), "****ef"));
assert(equal(tr(to!S("abcdef"), to!T("ef"), to!U(""), to!T("d")), "abcd"));
assert(equal(tr(to!S("hello goodbye"), to!T("lo"), to!U(""), to!U("s")), "helo godbye"));
assert(equal(tr(to!S("hello goodbye"), to!T("lo"), to!U("x"), "s"), "hex gxdbye"));
assert(equal(tr(to!S("14-Jul-87"), to!T("a-zA-Z"), to!U(" "), "cs"), " Jul "));
assert(equal(tr(to!S("Abc"), to!T("AAA"), to!U("XYZ")), "Xbc"));
}
}
auto s = to!S("hello world");
static assert(is(typeof(s) == typeof(tr(s, "he", "if"))));
}
});
}
/* ************************************************
* Version : v0.3
* Author : David L. 'SpottedTiger' Davis
* Date Created : 31.May.05 Compiled and Tested with dmd v0.125
* Date Modified : 01.Jun.05 Modified the function to handle the
* : imaginary and complex float-point
* : datatypes.
* :
* Licence : Public Domain / Contributed to Digital Mars
*/
/**
* [in] string s can be formatted in the following ways:
*
* Integer Whole Number:
* (for byte, ubyte, short, ushort, int, uint, long, and ulong)
* ['+'|'-']digit(s)[U|L|UL]
*
* examples: 123, 123UL, 123L, +123U, -123L
*
* Floating-Point Number:
* (for float, double, real, ifloat, idouble, and ireal)
* ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]]
* or [nan|nani|inf|-inf]
*
* examples: +123., -123.01, 123.3e-10f, 123.3e-10fi, 123.3e-10L
*
* (for cfloat, cdouble, and creal)
* ['+'|'-']digit(s)[.][digit(s)][[e-|e+]digit(s)][+]
* [digit(s)[.][digit(s)][[e-|e+]digit(s)][i|f|L|Li|fi]]
* or [nan|nani|nan+nani|inf|-inf]
*
* examples: nan, -123e-1+456.9e-10Li, +123e+10+456i, 123+456
*
* [in] bool bAllowSep
* False by default, but when set to true it will accept the
* separator characters "," and "_" within the string, but these
* characters should be stripped from the string before using any
* of the conversion functions like toInt(), toFloat(), and etc
* else an error will occur.
*
* Also please note, that no spaces are allowed within the string
* anywhere whether it's a leading, trailing, or embedded space(s),
* thus they too must be stripped from the string before using this
* function, or any of the conversion functions.
*/
bool isNumeric(const(char)[] s, in bool bAllowSep = false) @safe pure
{
ptrdiff_t iLen = s.length;
bool bDecimalPoint = false;
bool bExponent = false;
bool bComplex = false;
auto sx = std.string.toLower(s);
int j = 0;
char c;
//writefln("isNumeric(string, bool = false) called!");
// Empty string, return false
if (iLen == 0)
return false;
// Check for NaN (Not a Number)
if (sx == "nan" || sx == "nani" || sx == "nan+nani")
return true;
// Check for Infinity
if (sx == "inf" || sx == "-inf")
return true;
// A sign is allowed only in the 1st character
if (sx[0] == '-' || sx[0] == '+')
{
if (iLen == 1) // but must be followed by other characters
return false;
j++;
}
for (int i = j; i < iLen; i++)
{
c = sx[i];
// Digits are good, continue checking
// with the popFront character... ;)
if (c >= '0' && c <= '9')
continue;
// Check for the complex type, and if found
// reset the flags for checking the 2nd number.
else if (c == '+')
{
if (i > 0)
{
bDecimalPoint = false;
bExponent = false;
bComplex = true;
continue;
}
else
return false;
}
// Allow only one exponent per number
else if (c == 'e')
{
// A 2nd exponent found, return not a number
if (bExponent)
return false;
if (i + 1 < iLen)
{
// Look forward for the sign, and if
// missing then this is not a number.
if (sx[i + 1] != '-' && sx[i + 1] != '+')
return false;
else
{
bExponent = true;
i++;
}
}
else
// Ending in "E", return not a number
return false;
}
// Allow only one decimal point per number to be used
else if (c == '.' )
{
// A 2nd decimal point found, return not a number
if (bDecimalPoint)
return false;
bDecimalPoint = true;
continue;
}
// Check for ending literal characters: "f,u,l,i,ul,fi,li",
// and wheater they're being used with the correct datatype.
else if (i == iLen - 2)
{
// Integer Whole Number
if (sx[i..iLen] == "ul" &&
(!bDecimalPoint && !bExponent && !bComplex))
return true;
// Floating-Point Number
else if ((sx[i..iLen] == "fi" || sx[i..iLen] == "li") &&
(bDecimalPoint || bExponent || bComplex))
return true;
else if (sx[i..iLen] == "ul" &&
(bDecimalPoint || bExponent || bComplex))
return false;
// Could be a Integer or a Float, thus
// all these suffixes are valid for both
else if (sx[i..iLen] == "ul" ||
sx[i..iLen] == "fi" ||
sx[i..iLen] == "li")
return true;
else
return false;
}
else if (i == iLen - 1)
{
// Integer Whole Number
if ((c == 'u' || c == 'l') &&
(!bDecimalPoint && !bExponent && !bComplex))
return true;
// Check to see if the last character in the string
// is the required 'i' character
else if (bComplex)
if (c == 'i')
return true;
else
return false;
// Floating-Point Number
else if ((c == 'l' || c == 'f' || c == 'i') &&
(bDecimalPoint || bExponent))
return true;
// Could be a Integer or a Float, thus
// all these suffixes are valid for both
else if (c == 'l' || c == 'f' || c == 'i')
return true;
else
return false;
}
else
// Check if separators are allow
// to be in the numeric string
if (bAllowSep == true && (c == '_' || c == ','))
continue;
else
return false;
}
return true;
}
unittest
{
debug(string) printf("isNumeric(in string, bool = false).unittest\n");
assertCTFEable!(
{
// Test the isNumeric(in string) function
assert(isNumeric("1") == true );
assert(isNumeric("1.0") == true );
assert(isNumeric("1e-1") == true );
assert(isNumeric("12345xxxx890") == false );
assert(isNumeric("567L") == true );
assert(isNumeric("23UL") == true );
assert(isNumeric("-123..56f") == false );
assert(isNumeric("12.3.5.6") == false );
assert(isNumeric(" 12.356") == false );
assert(isNumeric("123 5.6") == false );
assert(isNumeric("1233E-1+1.0e-1i") == true );
assert(isNumeric("123.00E-5+1234.45E-12Li") == true);
assert(isNumeric("123.00e-5+1234.45E-12iL") == false);
assert(isNumeric("123.00e-5+1234.45e-12uL") == false);
assert(isNumeric("123.00E-5+1234.45e-12lu") == false);
assert(isNumeric("123fi") == true);
assert(isNumeric("123li") == true);
assert(isNumeric("--123L") == false);
assert(isNumeric("+123.5UL") == false);
assert(isNumeric("123f") == true);
assert(isNumeric("123.u") == false);
// @@@BUG@@ to!string(float) is not CTFEable.
// Related: formatValue(T) if (is(FloatingPointTypeOf!T))
if (!__ctfe)
{
assert(isNumeric(to!string(real.nan)) == true);
assert(isNumeric(to!string(-real.infinity)) == true);
assert(isNumeric(to!string(123e+2+1234.78Li)) == true);
}
string s = "$250.99-";
assert(isNumeric(s[1..s.length - 2]) == true);
assert(isNumeric(s) == false);
assert(isNumeric(s[0..s.length - 1]) == false);
});
assert(!isNumeric("-"));
assert(!isNumeric("+"));
}
/*****************************
* Soundex algorithm.
*
* The Soundex algorithm converts a word into 4 characters
* based on how the word sounds phonetically. The idea is that
* two spellings that sound alike will have the same Soundex
* value, which means that Soundex can be used for fuzzy matching
* of names.
*
* Params:
* string = String to convert to Soundex representation.
* buffer = Optional 4 char array to put the resulting Soundex
* characters into. If null, the return value
* buffer will be allocated on the heap.
* Returns:
* The four character array with the Soundex result in it.
* Returns null if there is no Soundex representation for the string.
*
* See_Also:
* $(LINK2 http://en.wikipedia.org/wiki/Soundex, Wikipedia),
* $(LUCKY The Soundex Indexing System)
*
* Bugs:
* Only works well with English names.
* There are other arguably better Soundex algorithms,
* but this one is the standard one.
*/
char[] soundex(const(char)[] string, char[] buffer = null) @safe pure nothrow
in
{
assert(!buffer || buffer.length >= 4);
}
out (result)
{
if (result)
{
assert(result.length == 4);
assert(result[0] >= 'A' && result[0] <= 'Z');
foreach (char c; result[1 .. 4])
assert(c >= '0' && c <= '6');
}
}
body
{
static immutable dex =
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
"01230120022455012623010202";
int b = 0;
char lastc;
foreach (char cs; string)
{ auto c = cs; // necessary because cs is final
if (c >= 'a' && c <= 'z')
c -= 'a' - 'A';
else if (c >= 'A' && c <= 'Z')
{
}
else
{
lastc = lastc.init;
continue;
}
if (b == 0)
{
if (!buffer)
buffer = new char[4];
buffer[0] = c;
b++;
lastc = dex[c - 'A'];
}
else
{
if (c == 'H' || c == 'W')
continue;
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
lastc = lastc.init;
c = dex[c - 'A'];
if (c != '0' && c != lastc)
{
buffer[b] = c;
b++;
lastc = c;
}
}
if (b == 4)
goto Lret;
}
if (b == 0)
buffer = null;
else
buffer[b .. 4] = '0';
Lret:
return buffer;
}
@safe pure nothrow unittest
{
assertCTFEable!(
{
char[4] buffer;
assert(soundex(null) == null);
assert(soundex("") == null);
assert(soundex("0123^&^^**&^") == null);
assert(soundex("Euler") == "E460");
assert(soundex(" Ellery ") == "E460");
assert(soundex("Gauss") == "G200");
assert(soundex("Ghosh") == "G200");
assert(soundex("Hilbert") == "H416");
assert(soundex("Heilbronn") == "H416");
assert(soundex("Knuth") == "K530");
assert(soundex("Kant", buffer) == "K530");
assert(soundex("Lloyd") == "L300");
assert(soundex("Ladd") == "L300");
assert(soundex("Lukasiewicz", buffer) == "L222");
assert(soundex("Lissajous") == "L222");
assert(soundex("Robert") == "R163");
assert(soundex("Rupert") == "R163");
assert(soundex("Rubin") == "R150");
assert(soundex("Washington") == "W252");
assert(soundex("Lee") == "L000");
assert(soundex("Gutierrez") == "G362");
assert(soundex("Pfister") == "P236");
assert(soundex("Jackson") == "J250");
assert(soundex("Tymczak") == "T522");
assert(soundex("Ashcraft") == "A261");
assert(soundex("Woo") == "W000");
assert(soundex("Pilgrim") == "P426");
assert(soundex("Flingjingwaller") == "F452");
assert(soundex("PEARSE") == "P620");
assert(soundex("PIERCE") == "P620");
assert(soundex("Price") == "P620");
assert(soundex("CATHY") == "C300");
assert(soundex("KATHY") == "K300");
assert(soundex("Jones") == "J520");
assert(soundex("johnsons") == "J525");
assert(soundex("Hardin") == "H635");
assert(soundex("Martinez") == "M635");
});
}
/***************************************************
* Construct an associative array consisting of all
* abbreviations that uniquely map to the strings in values.
*
* This is useful in cases where the user is expected to type
* in one of a known set of strings, and the program will helpfully
* autocomplete the string once sufficient characters have been
* entered that uniquely identify it.
* Example:
* ---
* import std.stdio;
* import std.string;
*
* void main()
* {
* static string[] list = [ "food", "foxy" ];
*
* auto abbrevs = std.string.abbrev(list);
*
* foreach (key, value; abbrevs)
* {
* writefln("%s => %s", key, value);
* }
* }
* ---
* produces the output:
* <pre>
* fox => foxy
* food => food
* foxy => foxy
* foo => food
* </pre>
*/
string[string] abbrev(string[] values) @safe pure
{
string[string] result;
// Make a copy when sorting so we follow COW principles.
values = values.dup.sort; // @@@BUG@@@ not CTFEable
size_t values_length = values.length;
size_t lasti = values_length;
size_t nexti;
string nv;
string lv;
for (size_t i = 0; i < values_length; i = nexti)
{
string value = values[i];
// Skip dups
for (nexti = i + 1; nexti < values_length; nexti++)
{
nv = values[nexti];
if (value != values[nexti])
break;
}
for (size_t j = 0; j < value.length; j += std.utf.stride(value, j))
{
string v = value[0 .. j];
if ((nexti == values_length || j > nv.length || v != nv[0 .. j]) &&
(lasti == values_length || j > lv.length || v != lv[0 .. j]))
{
result[v] = value;
}
}
result[value] = value;
lasti = i;
lv = value;
}
return result;
}
unittest
{
debug(string) printf("string.abbrev.unittest\n");
// @@@BUG@@@ Built-in arr.sort is not CTFEable
//assertCTFEable!(
//{
string[] values;
values ~= "hello";
values ~= "hello";
values ~= "he";
string[string] r;
r = abbrev(values);
auto keys = r.keys.dup;
keys.sort;
assert(keys.length == 4);
assert(keys[0] == "he");
assert(keys[1] == "hel");
assert(keys[2] == "hell");
assert(keys[3] == "hello");
assert(r[keys[0]] == "he");
assert(r[keys[1]] == "hello");
assert(r[keys[2]] == "hello");
assert(r[keys[3]] == "hello");
//});
}
/******************************************
* Compute column number after string if string starts in the
* leftmost column, which is numbered starting from 0.
*/
size_t column(S)(S str, size_t tabsize = 8) @safe pure if (isSomeString!S)
{
size_t column;
foreach (dchar c; str)
{
switch (c)
{
case '\t':
column = (column + tabsize) / tabsize * tabsize;
break;
case '\r':
case '\n':
case paraSep:
case lineSep:
column = 0;
break;
default:
column++;
break;
}
}
return column;
}
unittest
{
debug(string) printf("string.column.unittest\n");
assertCTFEable!(
{
assert(column(string.init) == 0);
assert(column("") == 0);
assert(column("\t") == 8);
assert(column("abc\t") == 8);
assert(column("12345678\t") == 16);
});
}
/******************************************
* Wrap text into a paragraph.
*
* The input text string s is formed into a paragraph
* by breaking it up into a sequence of lines, delineated
* by \n, such that the number of columns is not exceeded
* on each line.
* The last line is terminated with a \n.
* Params:
* s = text string to be wrapped
* columns = maximum number of _columns in the paragraph
* firstindent = string used to _indent first line of the paragraph
* indent = string to use to _indent following lines of the paragraph
* tabsize = column spacing of tabs
* Returns:
* The resulting paragraph.
*/
S wrap(S)(S s, size_t columns = 80, S firstindent = null,
S indent = null, size_t tabsize = 8) @safe pure if (isSomeString!S)
{
typeof(s.dup) result;
int spaces;
bool inword;
bool first = true;
size_t wordstart;
result.length = firstindent.length + s.length;
result.length = firstindent.length;
result[] = firstindent[];
auto col = column(result.idup, tabsize);
foreach (size_t i, dchar c; s)
{
if (std.uni.isWhite(c))
{
if (inword)
{
if (first)
{
}
else if (col + 1 + (i - wordstart) > columns)
{
result ~= '\n';
result ~= indent;
col = column(indent, tabsize);
}
else
{
result ~= ' ';
col += 1;
}
result ~= s[wordstart .. i];
col += i - wordstart;
inword = false;
first = false;
}
}
else
{
if (!inword)
{
wordstart = i;
inword = true;
}
}
}
if (inword)
{
if (col + 1 + (s.length - wordstart) >= columns)
{
result ~= '\n';
result ~= indent;
}
else if (result.length != firstindent.length)
result ~= ' ';
result ~= s[wordstart .. s.length];
}
result ~= '\n';
return result;
}
unittest
{
debug(string) printf("string.wrap.unittest\n");
assertCTFEable!(
{
assert(wrap(string.init) == "\n");
assert(wrap(" a b df ") == "a b df\n");
assert(wrap(" a b df ", 3) == "a b\ndf\n");
assert(wrap(" a bc df ", 3) == "a\nbc\ndf\n");
assert(wrap(" abcd df ", 3) == "abcd\ndf\n");
assert(wrap("x") == "x\n");
assert(wrap("u u") == "u u\n");
});
}
/******************************************
* Removes indentation from a multi-line string or an array of single-line strings.
*
* This uniformly outdents the text as much as possible.
* Whitespace-only lines are always converted to blank lines.
*
* A StringException will be thrown if inconsistent indentation prevents
* the input from being outdented.
*
* Works at compile-time.
*
* Example:
* ---
* writeln(q{
* import std.stdio;
* void main() {
* writeln("Hello");
* }
* }.outdent());
* ---
*
* Output:
* ---
*
* import std.stdio;
* void main() {
* writeln("Hello");
* }
*
* ---
*
*/
S outdent(S)(S str) @safe pure if(isSomeString!S)
{
return str.splitLines(KeepTerminator.yes).outdent().join();
}
/// ditto
S[] outdent(S)(S[] lines) @safe pure if(isSomeString!S)
{
if (lines.empty)
{
return null;
}
static S leadingWhiteOf(S str)
{
return str[ 0 .. $-find!(not!(std.uni.isWhite))(str).length ];
}
S shortestIndent;
foreach (i, line; lines)
{
auto stripped = __ctfe? line.ctfe_strip() : line.strip();
if (stripped.empty)
{
lines[i] = line[line.chomp().length..$];
}
else
{
auto indent = leadingWhiteOf(line);
// Comparing number of code units instead of code points is OK here
// because this function throws upon inconsistent indentation.
if (shortestIndent is null || indent.length < shortestIndent.length)
{
if (indent.empty)
return lines;
shortestIndent = indent;
}
}
}
foreach (i; 0..lines.length)
{
auto stripped = __ctfe? lines[i].ctfe_strip() : lines[i].strip();
if (stripped.empty)
{
// Do nothing
}
else if (lines[i].startsWith(shortestIndent))
{
lines[i] = lines[i][shortestIndent.length..$];
}
else
{
if (__ctfe)
assert(false, "outdent: Inconsistent indentation");
else
throw new StringException("outdent: Inconsistent indentation");
}
}
return lines;
}
// TODO: Remove this and use std.string.strip when retro() becomes ctfe-able.
private S ctfe_strip(S)(S str) if(isSomeString!(Unqual!S))
{
return str.stripLeft().ctfe_stripRight();
}
// TODO: Remove this and use std.string.strip when retro() becomes ctfe-able.
private S ctfe_stripRight(S)(S str) if(isSomeString!(Unqual!S))
{
size_t endIndex = 0;
size_t prevIndex = str.length;
foreach_reverse (i, dchar ch; str)
{
if (!std.uni.isWhite(ch))
{
endIndex = prevIndex;
break;
}
prevIndex = i;
}
return str[0..endIndex];
}
unittest
{
debug(string) printf("string.outdent.unittest\n");
template outdent_testStr(S)
{
enum S outdent_testStr =
"
\t\tX
\t\U00010143X
\t\t
\t\t\tX
\t ";
}
template outdent_expected(S)
{
enum S outdent_expected =
"
\tX
\U00010143X
\t\tX
";
}
assertCTFEable!(
{
static assert(ctfe_strip(" \tHi \r\n") == "Hi");
static assert(ctfe_strip(" \tHi©\u2028 \r\n") == "Hi©");
static assert(ctfe_strip("Hi") == "Hi");
static assert(ctfe_strip(" \t \r\n") == "");
static assert(ctfe_strip("") == "");
foreach (S; TypeTuple!(string, wstring, dstring))
{
enum S blank = "";
assert(blank.outdent() == blank);
static assert(blank.outdent() == blank);
enum S testStr1 = " \n \t\n ";
enum S expected1 = "\n\n";
assert(testStr1.outdent() == expected1);
static assert(testStr1.outdent() == expected1);
assert(testStr1[0..$-1].outdent() == expected1);
static assert(testStr1[0..$-1].outdent() == expected1);
enum S testStr2 = "a\n \t\nb";
assert(testStr2.outdent() == testStr2);
static assert(testStr2.outdent() == testStr2);
enum S testStr3 =
"
\t\tX
\t\U00010143X
\t\t
\t\t\tX
\t ";
enum S expected3 =
"
\tX
\U00010143X
\t\tX
";
assert(testStr3.outdent() == expected3);
static assert(testStr3.outdent() == expected3);
enum testStr4 = " X\r X\n X\r\n X\u2028 X\u2029 X";
enum expected4 = "X\rX\nX\r\nX\u2028X\u2029X";
assert(testStr4.outdent() == expected4);
static assert(testStr4.outdent() == expected4);
enum testStr5 = testStr4[0..$-1];
enum expected5 = expected4[0..$-1];
assert(testStr5.outdent() == expected5);
static assert(testStr5.outdent() == expected5);
enum testStr6 = " \r \n \r\n \u2028 \u2029";
enum expected6 = "\r\n\r\n\u2028\u2029";
assert(testStr6.outdent() == expected6);
static assert(testStr6.outdent() == expected6);
}
});
}
|