using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Test_SearchAndFind { class Search { /// /// Searches the specified string in a text /// /// Text to be searched. /// Character string to be searched. /// Should be ignored upper/lower case. /// Should only be searched for a whole word. public Search(string text, string searchString, bool noCaseSensitve, bool onlyFullWord) { Text = text; SearchString = searchString; NoCaseSensitve = noCaseSensitve; OnlyFullWord = onlyFullWord; SearchEntities(); CurrentCursorPosition = AllPositions[0]; Index = 0; } 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; } public int CurrentCursorPosition { set; get; } public List AllPositions { set; get; } public bool Error { 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; } public void NextPosition() { if (Index + 1 < AllPositions.Count) { Index++; } else { Index = 0; } CurrentCursorPosition = AllPositions[Index]; } public void PreviousPosition() { if (Index > 0) { Index--; } else { Index = AllPositions.Count - 1; } CurrentCursorPosition = AllPositions[Index]; } } }