4

Title pretty much explains itself, but let's say I have this:

string str1 = "microondas";
string str2 = "micrómetro";
bool comparison1 = str1.StartsWith("micro", StringComparison.InvariantCultureIgnoreCase);
bool comparison2 = str2.StartsWith("micro", StringComparison.InvariantCultureIgnoreCase);

However, comparison2 will return false. Is there an easy way to make it so it ignores diacritics, accents and tildes (so ó becomes o, ñ becomes n)? Bonus if it's also case insensitive.

I know there's CompareOptions.IgnoreNonSpace which does what I want, but I haven't found a way to implement it in StartsWith. Any help is appreciated!

Simon Zyx
  • 6,503
  • 1
  • 25
  • 37
  • 1
    Well, 'ó' and 'o' are two different characters – Fabjan Jun 09 '20 at 10:21
  • 1
    Does this answer your question? [Ignoring accented letters in string comparison](https://stackoverflow.com/questions/359827/ignoring-accented-letters-in-string-comparison) – Masoud Keshavarz Jun 09 '20 at 10:25
  • 1
    @MasoudKeshavarz String.Compare cannot answer whether it StartsWith something, and String.IndexOf does not have the required overload. – GSerg Jun 09 '20 at 10:29
  • @GSerg I just meant that PO could use provided `RemoveDiacritics` function from the link. Please see my answer. – Masoud Keshavarz Jun 09 '20 at 10:38
  • `Those do NOT answer my question at all!` - You clearly haven't looked at the duplicate. The very first line of the [accepted answer](https://stackoverflow.com/a/15178962/11683) goes, *You could use an appropriate CompareInfo and then CompareInfo.IndexOf(string, string, CompareOptions) and check the result against -1*. In your case, you need to check the result against 0. IndexOf of zero means it starts with the string. – GSerg Jun 09 '20 at 11:39

1 Answers1

3

You could try utilizing the System.Globalization.CompareInfo.IsPrefix method, which accepts a CompareOptions enum. See the docs here.

Besides this, you can try to manually implement it for youself based on for example this answer, which deals with removing diacritics from a string.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
  • Thank you so much. This worked perfectly. I ended up using CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase and did exactly what I wanted! –  Jun 09 '20 at 10:44