//KMP匹配串的位置 public int Index(StringLink s, int where = 1) { if (s.IsEmpty() || this.IsEmpty() || where < 1 || where > this.GetLength()) { Console.WriteLine("串不能为空或索引非法!"); return(0); } int[] nextval = this._GetNextVal(s); int matchLength = s.GetLength(); int length = this.GetLength(); int i = where; int j = 1; while (i <= length && j <= matchLength) { if (j == 0 || this[i] == s[j]) { j++; i++; } else { j = nextval[j]; } } if (j > matchLength) { return(i - matchLength); } return(0); }
private int[] _GetNextVal(StringLink s) { int length = s.GetLength(); int[] nextval = new int[length + 1]; int i = 1; int j = 0; nextval[1] = 0; for (; i < length;) { if (j == 0 || s[i] == s[j]) { i++; j++; if (s[i] == s[j]) { nextval[i] = nextval[j]; } else { nextval[i] = j; } } else { j = nextval[j]; } } return(nextval); }
//替换字符串 public int Replace(StringLink match, StringLink replace, int index = 1) { if (match.IsEmpty() || this.IsEmpty()) { Console.WriteLine("当前串或匹配串不能为空!"); return(0); } if (index < 1 || index > this.GetLength()) { Console.WriteLine("索引错误!"); return(0); } int matchIndex = this.Index(match, index); if (matchIndex != 0) { this.Delete(matchIndex, match.GetLength()); if (matchIndex - 1 == this.GetLength()) { this.Concat(replace); } else { this.Insert(matchIndex, replace); } return(1); } return(0); }
static void PrintStringLink(StringLink s, string text = "输出:") { Console.Write(text); for (int i = 0; i < s.GetLength(); i++) { Console.Write(s[i + 1]); } Console.WriteLine(); }