RingDotNetfor Ring

Comparing text

Is "apple" equal to "APPLE"? Which comes first, "Zebra" or "apple"? The answers depend on how you compare. This lesson shows ordinal and culture-aware comparison, comparers for sorting, dictionaries and sets that ignore case, and the famous Turkish "i".

What you will learn#

The tutorial Cultures formatted numbers and dates for a culture, and the tutorial Unicode and encodings looked at characters. This lesson is about comparing text, which every search box, sort order and dictionary of names needs.

The program#

samples/UsingDotNet/tutorials/ch02_comparers.ring
# comparing text - ordinal and culture comparison, ignoring case, StringComparer and a sorted set that ignores case
load "dotnet.ring"

using {
	"System"
	"System.Globalization"
	"System.Collections.Generic"
}

func main

	oString = new String()
	# 1. Two texts can be compared in different ways. Ordinal compares the code of every character: fast, exact, the same on every
	#    computer. Culture-aware comparison follows the rules of a language (in German "ä" is close to "a"). Both can ignore case.
	? "1. 'apple' = 'APPLE'"
	? "   ordinal:                " + (oString.Compare([ :strA = "apple", :strB = "APPLE", :comparisonType = "Ordinal" ]) = 0)
	? "   ordinal, ignore case:    " + (oString.Compare([ :strA = "apple", :strB = "APPLE", :comparisonType = "OrdinalIgnoreCase" ]) = 0)
	? "   invariant culture, ignore case: " + (oString.Compare([ :strA = "apple", :strB = "APPLE", :comparisonType = "InvariantCultureIgnoreCase" ]) = 0)

	# 2. The result of Compare is negative, zero or positive: only the SIGN means something
	? nl + "2. Compare('a','b') is negative: " + (oString.Compare([ :strA = "a", :strB = "b", :comparisonType = "Ordinal" ]) < 0)
	? "   Compare('b','a') is positive: " + (oString.Compare([ :strA = "b", :strB = "a", :comparisonType = "Ordinal" ]) > 0)

	# 3. Capital letters come before small letters in ordinal order (the code of "Z" is smaller than the code of "a"),
	#    a culture puts "a" and "A" next to each other
	oOrdinal = new StringComparer().Ordinal
	oCulture = new StringComparer().InvariantCulture
	oWords = new List([ :typeArguments = ["System.String"] ])
	for cWord in ["banana","Cherry","apple","Banana","cherry","Apple"]
		oWords.Add(cWord)
	next
	oWords.Sort(oOrdinal)
	? nl + "3. ordinal order:  " + joinList(oWords.toList())
	oWords.Sort(oCulture)
	? "   culture order:  " + joinList(oWords.toList())
	oWords.Sort(new StringComparer().OrdinalIgnoreCase)
	? "   ignore case:    " + joinList(oWords.toList()) + "   (equal words can come in any order)"

	# 4. A dictionary that ignores case: the comparer is the second argument of the constructor
	oPeople = new Dictionary([ :typeArguments = ["System.String","System.Int32"], :comparer = new StringComparer().OrdinalIgnoreCase ])
	oPeople.Add("Ann",31)
	? nl + "4. the key 'ANN' finds the key 'Ann': " + oPeople.ContainsKey("ANN")
	oPlain = new Dictionary([ :typeArguments = ["System.String","System.Int32"] ])
	oPlain.Add("Ann",31)
	? "   a plain dictionary does not: " + oPlain.ContainsKey("ANN")

	# 5. A sorted set with the same idea keeps one of 'Apple' and 'apple'
	oSet = new SortedSet([ :typeArguments = ["System.String"], :comparer = new StringComparer().OrdinalIgnoreCase ])
	for cWord in ["Apple","apple","Pear","APPLE","pear"]
		oSet.Add(cWord)
	next
	? nl + "5. " + oSet.Count + " words stay in the set: " + joinList(oSet.toList())

	# 6. The same letter is not the same in every culture. In Turkish the capital of "i" is "İ" (with a dot) and the small
	#    letter of "I" is "ı" (without a dot): upper-casing with the wrong culture breaks a comparison like "TITLE" = "title"
	oTurkish = new CultureInfo("tr-TR")
	? nl + "6. 'title' in capitals, invariant culture: " + upperText("title",new CultureInfo(""))
	? "   'title' in capitals, Turkish culture:   " + upperText("title",oTurkish)

func upperText cText,oCulture

	return oCulture.TextInfo.ToUpper(cText)

func joinList aList

	cText = ""
	for item in aList
		cText += "" + item + " "
	next
	return cText
Output
1. 'apple' = 'APPLE'
   ordinal:                0
   ordinal, ignore case:    1
   invariant culture, ignore case: 1

2. Compare('a','b') is negative: 1
   Compare('b','a') is positive: 1

3. ordinal order:  Apple Banana Cherry apple banana cherry 
   culture order:  apple Apple banana Banana cherry Cherry 
   ignore case:    apple Apple banana Banana cherry Cherry    (equal words can come in any order)

4. the key 'ANN' finds the key 'Ann': 1
   a plain dictionary does not: 0

5. 2 words stay in the set: Apple Pear 

6. 'title' in capitals, invariant culture: TITLE
   'title' in capitals, Turkish culture:   TİTLE
Note

This program uses a few generic functions (dnNewGeneric, callMethod) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Ordinal and culture#

Ordinal comparison looks at the number (code) of every character. It is exact and fast and gives the same answer on every computer, so it is the right choice for technical text: file names, identifiers, keys, protocols. Culture comparison follows the rules of a language: letters with accents are close to their base letters and a and A are neighbors. Use it for text that people read, such as a sorted list of names on the screen. The comparison type is an enum, so it is a text: "Ordinal", "OrdinalIgnoreCase", "InvariantCulture", "InvariantCultureIgnoreCase", "CurrentCulture".

The result of Compare#

String.Compare returns a number: negative when the first text comes first, zero when they are equal, positive when it comes second. Test only the sign (< 0, = 0, > 0) — the size is not defined. The method has many forms, so it takes named values (:strA, :strB, :comparisonType).

Sorting with a comparer#

A StringComparer object is a comparer: Sort(comparer) of a List uses it. In the ordinal order all capital letters come before all small ones (Apple Banana Cherry apple banana cherry), because the code of Z is smaller than the code of a. The culture order is the one that people expect (apple Apple banana Banana ...). With OrdinalIgnoreCase, apple and Apple are equal, so their order is not defined.

Note

The culture order comes from the operating system or the ICU library. It can differ a little between Windows, Linux and macOS, so a test or a file format must not depend on it.

Dictionaries and sets#

The constructor of a Dictionary or a SortedSet can take a comparer, and then all its lookups use it: with OrdinalIgnoreCase the key ANN finds Ann, and Apple, apple and APPLE count as one word in the set (the first one stays). This is the usual way to make a case-insensitive lookup table; it is much better than changing the case of every key by hand.

The Turkish i#

In Turkish there are two letters i: the one with a dot and the one without. The capital of i is İ (with a dot) and the small letter of I is ı. So "title".ToUpper() with the Turkish culture gives TİTLE, which is not equal to TITLE. A program that decides things by changing the case of text (a command name, a file extension) breaks on a Turkish computer if it uses the culture of the user. The rule: for technical comparison use ordinal comparison, or change the case with the invariant culture.

What you learned#

Exercises#

  1. Sort the file names of a folder (the tutorial Files and folders) in ordinal order and in culture order and look at the difference.
  2. Build a case-insensitive Dictionary of settings (the tutorial Settings).
  3. Compare "Straße" and "STRASSE" with the four comparison types.
  4. Write sameName(a, b) for user names that must ignore case and accents (look at CompareOptions).

Next#

Text readers and writers

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.