using System; using System.Collections.Generic; using System.Globalization; namespace PKHeX.Core { /// /// Utility for searching strings within arrays or within another string. /// public static class StringUtil { private static readonly CompareInfo CompareInfo = CultureInfo.CurrentCulture.CompareInfo; /// /// Finds the index of the string within the array by ignoring casing, spaces, and punctuation. /// /// Array of strings to search in /// Value to search for /// Index within public static int FindIndexIgnoreCase(string[] arr, string value) => Array.FindIndex(arr, z => IsMatchIgnoreCase(z, value)); /// /// Gets the indexes by calling for all . /// /// Array of strings to search in /// Items to search for /// Index within public static int[] GetIndexes(string[] arr, IReadOnlyList items) => GetIndexes(arr, items, 0, items.Count); /// /// Gets the indexes by calling for all . /// /// Array of strings to search in /// Items to search for /// Starting index within /// Amount to convert within /// Index within public static int[] GetIndexes(string[] arr, IReadOnlyList items, int start, int length) { if (length < 0) length = items.Count - start; var result = new int[length]; for (int i = 0; i < result.Length; i++) result[i] = FindIndexIgnoreCase(arr, items[start + i]); return result; } private static bool IsMatchIgnoreCase(string string1, string string2) { if (string1.Length != string2.Length) return false; const CompareOptions options = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth; var compare = CompareInfo.Compare(string1, string2, options); return compare == 0; } /// /// Gets the string entry within the input , based on the and position. /// public static string GetNthEntry(string line, int nth, int start, char separator = ',') { if (nth != 1) start = line.IndexOfNth(separator, nth - 1, start + 1); var end = line.IndexOfNth(separator, 1, start + 1); return end < 0 ? line.Substring(start + 1) : line.Substring(start + 1, end - start - 1); } private static int IndexOfNth(this string s, char t, int n, int start) { int count = 0; for (int i = start; i < s.Length; i++) { if (s[i] != t) continue; if (++count == n) return i; } return -1; } } }