How to Compare localized strings in C# - c#

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.

Related

How to compare in IF condition

I am returning a value from SQL. Let's give it a name as ReturnedFromSQL. In my application, I am giving an input. Let's give it a name as Input. I want to compare these two and do an activity. Currently, I am doing this with an IFcondition.
Let's say, from SQL I am getting FAB01and as the Input I am getting Fab01. What I want to do is to jump to ELSEpart after comparing these two if these two are not same and execute IF part if these two are same.
It is obvious that just the letters have changed but the idea is same. Since these two are same, I need to execute what is in IFpart instead of jumping to ELSE. But it is not happening now. How do I do that? Can anyone help me? Thank you in advance.
IF (ReturnedFromSQL == Input )
{
return RedirectToAction("Exist");
}
else
{
//Doing Something
}
Assuming that both ReturnedFromSQL and Input are strings. This code will convert both the value to lower for comparison so no issue if any of the string has same character but in different level(upper/lower)
if (ReturnedFromSQL.ToLower().Trim() == Input.ToLower().Trim() )
{
return RedirectToAction("Exist");
}
else
{
//Doing Something
}
You can use string.Equals(). The best part is that you do not need to trim or lowercase explicitly.
if(string.Equals(ReturnedFromSQL, Input, StringComparison.CurrentCultureIgnoreCase))
{
return RedirectToAction("Exist");
}
Take care if you follow the advice in some of the other answers. ToLower() is only safe in English and a handful of other languages. In many languages, there may be multiple upper/lower case representations of the same letter or letter combination, or certain accents may be considered equal or not equal, breaking such logic. There be the dragons.
Try this instead, changing the StringComparison as per your use case:
using System;
public class Program
{
public static void Main()
{
string ReturnedFromSQL = "FAB01";
string Input = "Fab01";
if (String.Equals(ReturnedFromSQL, Input, StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("Equal");
}
else
{
Console.WriteLine("Different");
}
}
}
if both values are string then you can apply ToLower() and Trim() (as in x.Trim().ToLower()) functions on both party in order to have a unified value. but even without that you still should be good, so i guess the problem is something else. i advise debugging the condition and check the value of both sides and see if either one is null or empty.
Your condition can use Equals
if (String.Equals(ReturnedFromSQL, Input, StringComparison.OrdinalIgnoreCase))

Why does "\u1FFF:foo".StartsWith(":") return true?

The string "\u1FFF:foo" starts with \u1FFF (or "῿"), right?
So how can these both be true?
"\u1FFF:foo".StartsWith(":") // equals true
"\u1FFF:foo".StartsWith("\u1FFF") // equals true
// alternatively, the same:
"῿:foo".StartsWith(":") // equals true
"῿:foo".StartsWith("῿") // equals true
Does .NET claim that this string starts with two different characters?
And while I find this very surprising and would like to understand the "why", I'm equally interested in how I can force .NET to search exclusively by codepoints instead (using InvariantCulture doesn't seem to do a thing)?
And for comparison, one characters below that, "\u1FFE:foo".StartsWith(":") returns false.
That a string in general might be considered to start with two different strings that are not byte-for-byte identical is not surprising (because Unicode is complicated). For example, these results are almost always going to reflect what a user wants:
"n\u0303".StartsWith("\u00f1") // true
"n\u0303".StartsWith("n") // false
Using System.Globalization.CharUnicodeInfo.GetUnicodeCategory, you can see that '\u1fff' is in the "OtherNotAssigned" category; it's unclear to me whether that should affect string search/sort/comparison operations (it does not appear to affect normalization, that is, the characters remain after normalization).
If you want a byte-for-byte comparison, use StringComparison.Ordinal.
Because you are using String.StartsWith() incorrectly. You should use String.StartsWith (String, StringComparison) overload and StringComparison.Ordinal.
There is no character assigned to \u1FFF. I.e. there is no linguistic meaning attached to this code. See Greek Extended, Range: 1F00–1FFF excerpt from character code tables for Unicode Standard. Best Practices for Using Strings in .NET document from MSDN explicitly states that if you need to compare strings in a manner that ignores features of natural languages then you should use StringComparison.Ordinal:
Specifying the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase value in a method call signifies a non-linguistic comparison in which the features of natural languages are ignored. Methods that are invoked with these StringComparison values base string operation decisions on simple byte comparisons instead of casing or equivalence tables that are parameterized by culture. In most cases, this approach best fits the intended interpretation of strings while making code faster and more reliable.
Moreover, it recommends to always explicitly specify StringComparison in such method calls:
When you develop with .NET, follow these simple recommendations when you use strings:
Use overloads that explicitly specify the string comparison rules for string operations. Typically, this involves calling a method overload that has a parameter of type StringComparison.

String.Contains and String.LastIndexOf C# return different result?

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 :) ).

Stringcomparison OrdinalIgnoreCase for true false values

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.

String Case Sensitivity [duplicate]

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)

Categories

Resources