// this program showcases some of the capabilities of the // stringutil header. // // compile and run : g++ test_stringutil.cc ; a.out #include "foreach.hh" #include "stringutil.hh" using namespace stringutil; #include #include #include #include #include #include using namespace std; const string red = "\x1b[41m"; int main() { // -- printing -- print ( split("a b c ") ); print ( split("").size() ); print ( "42 =", 42, " and 9*7=", 9*8 ); print ("function","style"); // -- trim -- assert ( trim("\t \nxx ") == "xx" ); // -- contains, endswith and startswith --- assert ( contains("abcd", "bc") == true ); assert ( contains("abcd", "") == true ); assert ( contains("", "") == true ); assert ( contains("", "a") == false ); assert ( endswith("hallo ik ben theo","theo") == true ); assert ( endswith("hallo ik ben the ","theo") == false ); assert ( endswith("hallo ik ben the ","") == true ); assert ( endswith("","a") == false ); assert ( endswith("","") == true ); assert ( endswith("theo theo theo","theo") == true ); assert ( endswith("b b b","b") == true ); assert ( startswith("ab","a") == true ); assert ( startswith("","a") == false); assert ( startswith("a","") == true ); // -- lexical conversions --- assert ( to(1) == "1" ); assert ( to("2") == 2.0 ); assert ( to("42") == 42 ); assert ( to("42.1") == 42 ); // prints a warning, but sill okay assert ( is_a (" 4.25 ") == true ); // true - spaces are ignored assert ( is_num("1e3") == true ); // true : shorthand for is_a assert ( is_a (" 4.25 ") == false ); // false - 4 is read, but .25 remains assert ( is_a (" a b c ") == false ); // false, since something is left after reading a. (!!) -> not very useful // -- string split function --- assert ( split("a b c") == vector ( {"a","b","c"} )); assert ( split("a b c") == vector ( {"a","","b","c"} )); assert ( split("a b c "," ", 1) == vector ( {"a","b c "} )); // -- string joining --- assert ( join ( " ", split ( "a b c d" )) == "a b c d" ); // join uses operator<< inside and is templated, so this also works vector W = range(1,10); auto s = join("+",W) + " = " + str(sum(W)); print(s); assert ( s == "1+2+3+4+5+6+7+8+9 = 45"); // -- get substrings --- assert ( get_substring ("xabbcx","a","c") == "bb" ); assert ( get_substring ("xabbcx","a","") == "bbcx" ); assert ( get_substring ("xabbcx","","c") == "xabb" ); assert ( get_substring ("xabbax","a","a") == "bb" ); // it looks from the right for the end assert ( get_substring ("xabbax","a","a", true) == "abba" ); // formatting, printf style string s3 = form("the %s is %5.4f", "answer", 42.0 ); assert (s3 == "the answer is 42.0000" ); // debugging and fatal errors macro's dbg( s3 ); try { fatal("this is the error" "message", "for fatal", 42); assert(false); // should not get here. } catch (AAFatalException) { cout << "exception caught as expected" << endl; } exit(0); // success. }