test-replace.nut 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. local str = "a day in life";
  2. print(str.replace("day", "night"));
  3. function my_find_close_quote(src, init=0){
  4. local src_size = str.len();
  5. if(init >= src_size) throw "invalid start position";
  6. for(; init < src_size; ++init) {
  7. if(src[init] == '"'){
  8. if(init < (src_size-1) && src[init+1] == '"') ++init; //skip quoted quote
  9. else break;
  10. }
  11. }
  12. if(src[init] != '"') init = -1;
  13. return init;
  14. }
  15. // Convert from CSV string to table
  16. function fromCSV (s){
  17. local t = []; // table to collect fields
  18. local fieldstart = 0;
  19. local slen = s.len();
  20. do {
  21. // next field is quoted? (start with `"'?)
  22. if (s[fieldstart] == '"') {
  23. local i = s.find_close_quote(fieldstart+1);
  24. //local i = my_find_close_quote(s, fieldstart+1);
  25. if (i<0) throw("unmatched \"");
  26. local f = s.slice(fieldstart+1, i);
  27. //print(f);
  28. t.push(f.replace("\"\"", "\""));
  29. local nextc = s.find(",", i);
  30. if(!nextc) nextc=slen-1;
  31. fieldstart = nextc + 1;
  32. }
  33. else // unquoted; find next comma
  34. {
  35. local nexti = s.find(",", fieldstart);
  36. if(!nexti) nexti = slen-1;
  37. //print("nn", s.slice(fieldstart, nexti))
  38. t.push(s.slice(fieldstart, nexti));
  39. fieldstart = nexti + 1;
  40. }
  41. } while(fieldstart < slen);
  42. return t;
  43. }
  44. str = "12,345.9,leon,,234.56,9,32,44444444444444444444444444444444444444444444444444444444444444444444444444444444444444,\"Domingo\"\",,\"tais\",leon,,234.56,9,32,44,\"laura\"";
  45. //str = [=[
  46. //"""ARTHUR BALFOUR"",CONSERVATIVE WORKING MEN'S CLUB LIMITED","IP10067R","","","","","","","","","Industrial and Provident Society","Active","United Kingdom","","01/01/1981","","","","","NO ACCOUNTS FILED","","","0","0","0","0","None Supplied","","","","0","0","http://business.data.gov.uk/id/company/IP10067R","","","","","","","","","","","","","","","","","","","",""]=];
  47. local ar2 = fromCSV(str);
  48. print(ar2.len());
  49. foreach(i, s in ar2) print(i,s);
  50. local ar
  51. local now = os.clock();
  52. for(local i=0; i< 100000; ++i){
  53. ar = fromCSV(str);
  54. }
  55. print("Spent", os.clock()-now)
  56. print(ar.len());
  57. foreach( i, s in ar) print(s);
  58. local pos;
  59. now = os.clock();
  60. for(local i=0; i< 100000; ++i){
  61. pos = str.find_close_quote();
  62. }
  63. print("Spent native", os.clock()-now)
  64. now = os.clock();
  65. for(local i=0; i< 100000; ++i){
  66. pos = my_find_close_quote(str);
  67. }
  68. print("Spent interpreted", os.clock()-now)
  69. os.exit();