请看KMP代码:
function KMP(s, m, p, n) { if (n == 0 || m == 0) return; split(s, str, ""); split(p, pattern, ""); # https://www.tutorialspoint.com/awk/awk_string_functions.htm # split返回的数组,[0]是"",所以下面是PASCAL版 # https://blog.csdn.net/idler/article/details/4846 j = 1; k = 0; while (j < n) { if ( k == 0 || pattern[j] == pattern[k] ) { j = j + 1; k = k + 1; na[j] = k; /* next是关键字 */ } else k = na[k]; } for (i = j = 1; i <= m;) { # 不支持,表达式,不支持// if ( j == 0 || str[i] == pattern[j] ) { i++; ++j; } else j = na[j]; if (j > n) { printf("%d\n", i - n - 1); j = 1; } } } BEGIN { # awk doen't support variables local to functions _str = "AABACAABAAAABAA12345AABAA"; _ptn = "AABAA"; m = length(_str); n = length(_ptn); # m长得像nn, 所以比较长 KMP(_str, m, _ptn, n); }
数组是关联数组/map:
BEGIN { str = "a b\tc de" # 语句不用;结尾 split(str, ary, "[ \t]+") # C还得用外部库 for (i in ary) printf("%d %s\n", i, ary[i]) print # 比puts(""); 短 for (i = 0; i < length(ary); i++) printf("%d %s\n", i, ary[i]) ary["tom"] = "cat"; ary[3.14] = 5678 # 关联数组/map print; print(ary["tom"], ary[3.14]) }
MadEdit有语法高亮:
gawk -f t.awk
https://files.cnblogs.com/files/blogs/714801/gawk.7z 176KB 含且仅含 gawk.exe 461KB
标签:ptn,ary,算法,PASCAL,awk,split,str,printf From: https://www.cnblogs.com/funwithwords/p/17001210.html