/// <summary> /// 匹配词段 /// </summary> /// <param name="charArray"></param> /// <param name="begin"></param> /// <param name="length"></param> /// <param name="searchHit"></param> /// <returns></returns> public Hit Match(char[] charArray, int begin, int length, Hit searchHit) { if (searchHit == null) { //如果hit为空,新建 searchHit = new Hit(); //设置hit的其实文本位置 searchHit.Begin = begin; } else { //否则要将HIT状态重置 searchHit.SetUnmatch(); } //设置hit的当前处理位置 searchHit.End = begin; char keyChar = charArray[begin]; // TODO:代码不同 DictionarySegment ds = null; //引用实例变量为本地变量,避免查询时遇到更新的同步问题 DictionarySegment[] segmentArray = this.childrenArray; Dictionary<char, DictionarySegment> segmentMap = this.childrenMap; //STEP1 在节点中查找keyChar对应的DictionarySegment if (segmentArray != null) { //在数组中查找 foreach (DictionarySegment seg in segmentArray) { if (seg != null && seg.nodeChar.Equals(keyChar)) { //找到匹配的段 ds = seg; } } } else if (segmentMap != null) { //在map中查找 if (segmentMap.ContainsKey(keyChar)) ds = segmentMap[keyChar]; } //STEP2 找到DictionarySegment,判断词的匹配状态,是否继续递归,还是返回结果 if (ds != null) { if (length > 1) { //词未匹配完,继续往下搜索 return ds.Match(charArray, begin + 1, length - 1, searchHit); } else if (length == 1) { //搜索最后一个char if (ds.nodeState == 1) { //添加HIT状态为完全匹配 searchHit.SetMatch(); } if (ds.HasNextNode) { //添加HIT状态为前缀匹配 searchHit.SetPrefix(); //记录当前位置的DictionarySegment searchHit.MatchedDictionarySegment = ds; } return searchHit; } } //STEP3 没有找到DictionarySegment, 将HIT设置为不匹配 return searchHit; }
/// <summary> /// 检索匹配主词典, /// 从已匹配的Hit中直接取出DictionarySegment,继续向下匹配 /// </summary> public static Hit MatchWithHit(char[] charArray, int currentIndex, Hit matchedHit) { DictionarySegment ds = matchedHit.MatchedDictionarySegment; return ds.Match(charArray, currentIndex, 1, matchedHit); }