using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Test_SearchAndFind { /// /// Searches the specified string in a text /// class Search { public void StartSearch(string text, string searchString, bool noCaseSensitve, bool onlyFullWord) { Text = text; SearchString = searchString; NoCaseSensitve = noCaseSensitve; OnlyFullWord = onlyFullWord; SearchEntities(); if (!Error) { CurrentCursorPosition = AllPositions[0]; Index = 0; } else { //Suchstring wurde nicht gefunden throw new StringNotMatchException(); } } private string Text { set; get; } private string SearchString { set; get; } private bool NoCaseSensitve { set; get; } private bool OnlyFullWord { set; get; } public int Index { private set; get; } /// /// Contains the current cursor position /// public int CurrentCursorPosition { private set; get; } /// /// Contains a list with all found positions /// public List AllPositions { private set; get; } /// /// Is true if an error has occurred /// public bool Error { private set; get; } private void SearchEntities() { Error = false; string text = Text; string searchString = SearchString; if (NoCaseSensitve) { //Groß-/Kleinschreibung ignorieren text = text.ToLower(); searchString = searchString.ToLower(); } if (!String.IsNullOrEmpty(searchString) && text.Contains(searchString)) { AllPositions = Positions(text, searchString); } else { Error = true; } } private List Positions(string text, string searchString) { List positions = new List(); if (String.IsNullOrEmpty(text) || String.IsNullOrEmpty(searchString)) { return positions; } int position = 0; int currentPos = 0; while (text.Contains(searchString)) { if (OnlyFullWord) { //Nur ganzes Wort suchen currentPos = IndexOfWord(text, searchString); } else { //Suchstring suchen currentPos = text.IndexOf(searchString); } position += currentPos; positions.Add(position); position += searchString.Length; text = text.Remove(0, currentPos + searchString.Length); } return positions; } private Regex myRegex; private int IndexOfWord(string myString, string myWord) { myRegex = new Regex("\\b" + Regex.Escape(myWord) + "\\b", RegexOptions.Compiled); Match mtch = myRegex.Match(myString); if (mtch.Success) return mtch.Index; else return -1; } /// /// Jumps to the next occurrence position /// public void NextPosition() { if (Index + 1 < AllPositions.Count) { Index++; } else { Index = 0; } CurrentCursorPosition = AllPositions[Index]; } /// /// Jumps to previous occurrence position /// public void PreviousPosition() { if (Index > 0) { Index--; } else { Index = AllPositions.Count - 1; } CurrentCursorPosition = AllPositions[Index]; } } #region Exceptions public class StringNotMatchException : Exception { public StringNotMatchException() { } public StringNotMatchException(string message) : base(message) { } public StringNotMatchException(string message, Exception inner) : base(message, inner) { } } #endregion }