This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is there a C# case insensitive equals operator?
string string1 = "aBc"
string string2 = "AbC"
how can I check if string1 is equal to string2 and have it return true, regardless of case sensitivity.
Two approaches:
You can .ToLower() and do string-equality, or you can use this:
string.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase)
Edit: To appease the downvoters, this operation is useful if your data is culturally significant (i.e., you're comparing Scandinavian words and your current locale is set correctly). If this data is culturally agnostic, and you don't care about locales (bad idea, particularly since .NET lives for Unicode), you can do this:
string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase)
You should use the recommendations here MSDN: "Recommendations for String Use" :
DO: Use StringComparison.Ordinal or OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
DO: Use StringComparison.Ordinal and OrdinalIgnoreCase comparisons for increased speed.
DO: Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.
DO: Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is linguistically irrelevant (symbolic, for example).
DO: Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.
DON'T: Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
DON'T: Use StringComparison.InvariantCulture-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.
I must admit they were an eyeopener for me. Especially the last one.
You can also use string.Compare, adding the third parameter, which is ignoreCase:
if (string.Compare(string1, string2, true) == 0)
{
// string are equal
}
And you could use also the CompareInfo class:
if (CultureInfo.CurrentCulture.CompareInfo.Compare(string1, string2,
CompareOptions.IgnoreCase) == 0)
{
// string are equal
}
string.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);
:D
string.Equals("aBc", "AbC", StringComparison.CurrentCultureIgnoreCase)
Related
in persian/arabic character, some character used optional on top or bottom of other character like ِ َ ّ ُ.
in my example if i use this character, indexOf not found my word. consider that persian/arabic is rtl language.
for example:
منّم => م + ن + ّ + م
C#:
"منّم".IndexOf("من");
return -1
javascript:
var index= ' منّم '.indexOf('من');
console.log(index);
what happened in C#. anyone can explain this?
By passing in StringComparison.Ordinal as an argument to the overloaded String.IndexOf(), you could have also done the following:
"منّم".IndexOf("من", StringComparison.Ordinal); // returns 0
Specifying CompareOptions.Ordinal as an option should work, together with the IndexOf method of CompareInfo.
CompareInfo info = CultureInfo.CurrentCulture.CompareInfo;
string str = "منّم";
Console.WriteLine(info.IndexOf(str, "من", CompareOptions.Ordinal));
Output is 0.
DotNetFiddle if you want to try it yourself.
You should learn about the different methods that .Net uses to compare/match strings.
Best Practices for Using Strings in .NET
Some overloads with default parameters (those that search for a Char
in the string instance) perform an ordinal comparison, whereas others
(those that search for a string in the string instance) are
culture-sensitive. It is difficult to remember which method uses which
default value, and easy to confuse the overloads.
The section String Operations that Use the Invariant Culture gives a short explanation about combining characters.
I would like to compare two strings containing file paths in c#.
However, since in ntfs the default is to use case insensitive paths, I would like the string comparison to be case insensitive in the same way.
However I can't seem to find any information on how ntfs actually implements its case insensitivity. What I would like to know is how to perform a case insensitive comparison of strings using the same casing rules that ntfs uses for file paths.
From MSDN:
The string behavior of the file system, registry keys and values, and environment variables is best represented by StringComparison.OrdinalIgnoreCase.
And:
When interpreting file names, cookies, or anything else where a combination such as "å" can appear, ordinal comparisons still offer the most transparent and fitting behavior.
Therefore it's simply:
String.Equals(fileNameA, fileNameB, StringComparison.OrdinalIgnoreCase)
(I always use the static Equals call in case the left operand is null)
While comparison of paths the path's separator direction is also very important. For instance:
bool isEqual = String.Equals("myFolder\myFile.xaml", "myFolder/myFile.xaml", StringComparison.OrdinalIgnoreCase);
isEqual will be false.
Therefore needs to fix paths first:
private string FixPath(string path)
{
return path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.ToUpperInvariant();
}
Whereas this expression will be true:
bool isEqual = String.Equals(FixPath("myFolder\myFile.xaml"), FixPath("myFolder/myFile.xaml"), StringComparison.OrdinalIgnoreCase);
string path1 = "C:\\TEST";
string path2 = "c:\\test";
if(path1.ToLower() == path2.ToLower())
MessageBox.Show("True");
Do you mean this or did i not get the question?
I would go for
string.Compare(path1, path2, true) == 0
or if you want to specify cultures:
string.Compare(path1, path2, true, CultureInfo.CurrentCulture) == 0
using ToUpper does a useless memory allocation every time you compare something
I have this problem where String.Contains returns true and String.LastIndexOf returns -1. Could someone explain to me what happened? I am using .NET 4.5.
static void Main(string[] args)
{
String wikiPageUrl = #"http://it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl";
if (wikiPageUrl.Contains("wikipedia.org/wiki/"))
{
int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki/");
Console.WriteLine(i);
}
}
While #sa_ddam213's answer definitely fixes the problem, it might help to understand exactly what's going on with this particular string.
If you try the example with other "special characters," the problem isn't exhibited. For example, the following strings work as expected:
string url1 = #"http://it.wikipedia.org/wiki/»Abd_Allāh_al-Sallāl";
Console.WriteLine(url1.LastIndexOf("it.wikipedia.org/wiki/")); // 7
string url2 = #"http://it.wikipedia.org/wiki/~Abd_Allāh_al-Sallāl";
Console.WriteLine(url2.LastIndexOf("it.wikipedia.org/wiki/")); // 7
The character in question, "ʿ", is called a spacing modifier letter1. A spacing modifier letter doesn't stand on its own, but modifies the previous character in the string, this case a "/". Another way to put this is that it doesn't take up its own space when rendered.
LastIndexOf, when called with no StringComparison argument, compares strings using the current culture.
When strings are compared in a culture-sensitive manner, the "/" and "ʿ" characters are not seen as two distinct characters--they're processed into one character, which does not match the parameter passed in to LastIndexOf.
When you pass in StringComparison.Ordinal to LastIndexOf, the characters are treated as distinct, due to the nature of Ordinal comparison.
Another way to make this work would be to use CompareInfo.LastIndexOf and supply the CompareOptions.IgnoreNonSpace option:
Console.WriteLine(
CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(
wikiPageUrl, #"it.wikipedia.org/wiki/", CompareOptions.IgnoreNonSpace));
// 7
Here we're saying that we don't want combining characters included in our string comparison.
As a sidenote, this means that #Partha's answer and #Noctis' answer only work because the character is being applied to a character that doesn't appear in the search string that's passed to LastIndexOf.
Contrast this with the Contains method, which by default performs an Ordinal (case sensitive and culture insensitive) comparison. This explains why Contains returns true and LastIndexOf returns false.
For a fantastic overview of how strings should be manipulated in the .NET framework, check out this article.
1: Is this different than a combining character or is it a type of combining character? would appreciate if someone would clear that up for me.
Try using StringComparison.Ordinal
This will compare the string by evaluating the numeric values of the corresponding chars in each string, this should work with the special chars you have in that example string
string wikiPageUrl = #"http://it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl";
int i = wikiPageUrl.LastIndexOf("http://it.wikipedia.org/wiki/", StringComparison.Ordinal);
// returns 0;
The thing is C# lastindexof looks from behind.
And wikipedia.org/wiki/ is followed by ' which it takes as escape sequence. So either remove ' after wiki/ or have an # there too.
The following syntax will work( anyone )
string wikiPageUrl = #"http://it.wikipedia.org/wiki/Abd_Allāh_al-Sallāl";
string wikiPageUrl = #"http://it.wikipedia.org/wiki/#ʿAbd_Allāh_al-Sallāl";
int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki");
All 3 works
If you want a generalized solution for this problem replace ' with #' in your string before you perform any operations.
the ' characters throws it off.
This should work, when you escape the ' as \':
wikiPageUrl = #"http://it.wikipedia.org/wiki/\'Abd_Allāh_al-Sallāl";
if (wikiPageUrl.Contains("wikipedia.org/wiki/"))
{
"contains".Dump();
int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki/");
Console.WriteLine(i);
}
figure out what you want to do (remove the ', escape it, or dig deeper :) ).
I am doing localization for ASP.NET Web Application, when user enters a localized string "XXXX" and i am comparing that string with a value in my localized resource file.
Example :
if ( txtCalender.Text == Resources.START_NOW)
{
//do something
}
But When i do that even when the two strings(localized strings) are equal, it returns false. ie.
txtCalender.Text ="இப்போது தொடங்க"
Resources.START_NOW="இப்போது தொடங்க"
This is localized for Tamil.
Please help..
Use one of the string.Equals overloads that takes a StringComparison value - this allows you to use the current culture for comparison..
if ( txtCalender.Text.Equals(Resources.START_NOW, StringComparison.CurrentCulture))
{
//do something
}
Or, if you want case insensitive comparison:
if ( txtCalender.Text.Equals(Resources.START_NOW,
StringComparison.CurrentCultureIgnoreCase))
{
//do something
}
I found the answer and it works. Here is the solution,
it was not working when i tried from Chrome browser and it works with Firefox. Actually when i converted both string to char array,
txtCalender.Text Returns 40 characters and Resource.START_NOW returned 46. So i have tried to Normalize the string using Normalize() method
if(txtCalender.Text.Normalize() == Resources.START_NOW.Normalize())
It was interpreting one character as two different characters when i didn't put normalize method.
it has worked fine. Thanks for your answers.
You can compare with InvariantCulture in String.Equals (statis method):
String.Equals("XXX", "XXX", StringComparison.InvariantCulture);
Not sure whether this helps though, could others comment on it? I've never come across your actual error.
Use String.Equals or String.Compare.
There is some performance differences between these two. String.Compare is faster than String.Equal because String.Compare is static method and String.Equals is instance method.
String.Equal returns a boolean. String.Compare returns 0 when the strings equal, but if they're different they return a positive or negative number depending on whether the first string is before (less) or after (greater) the second string. Therefore, use String.Equals when you need to know if they are the same or String.Compare when you need to make a decision based on more than equality.
You probably need to use .Equals
if(txt.Calendar.Text.Equals(Resources.START_NOW))
{ //...
And if case-insensitive comparison is what you're after (often is) use StringComparison.OrdinalIgnoreCase as the second argument to the .Equals call.
If this isn't working - then can I suggest you breakpoint the line and check the actual value of Resources.START_NOW - the only possible reason why this equality comparison would fail is if the two strings really aren't the same. So my guess is that your culture management isn't working properly.
Does this make sense? MyValue can be "true" or "false"
Should it not be Stringcomparison.OrdinalIgnoreCase ?
MyValue.Equals("true", StringComparison.CurrentCultureIgnoreCase))
I would not do that. Just because a string is not equal to "true" does not mean it's equal to "false". This is an easy way to let ugly bugs slip in. I think you should parse the string
bool value;
if(!Boolean.TryParse(MyValue, out value)) {
// it did not parse
}
// it parsed
This is more likely to be correct, and it's more readable. Plus, culture issues just got swept under the rug.
It really depends on your situation and how the rest of your program is crafted. From the docs on OrdinalCompareCase
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames.
So basically, if the values are culture independent (generated progamatically, etc) use OrdinalIgnoreCase
Bool.Parse
looks better to me.