C#.NET strings: What will be printed by the following code when comparing two differently cased strings? String s1 = 'Five Star'; String s2 = 'FIVE STAR'; int c; c = s1.CompareTo(s2); Console.WriteLine(c); Choose the correct result of the call to CompareTo (case-sensitive, culture-aware comparison).

Difficulty: Easy

Correct Answer: 1

Explanation:


Introduction / Context:
This question examines how String.CompareTo behaves in C#.NET. The method performs a case-sensitive, culture-aware comparison and returns an integer: less than 0 if the instance precedes the argument, 0 if equal, and greater than 0 if it follows.



Given Data / Assumptions:

  • s1 = 'Five Star'
  • s2 = 'FIVE STAR'
  • c = s1.CompareTo(s2) and then Console.WriteLine(c)
  • CompareTo returns a signed int, not necessarily only -1, 0, or 1, but commonly those values.


Concept / Approach:
Comparison is lexicographic and case-sensitive in the current culture. The first differing character controls the result. Uppercase and lowercase letters have different sort values; typically lowercase letters follow uppercase in case-sensitive comparisons.



Step-by-Step Solution:

Compare character by character: 'F' vs 'F' → equal.Next: 'i' (105) vs 'I' (73) → since 105 > 73, s1 is greater than s2.Therefore, CompareTo returns a positive integer. In typical outputs this prints 1.


Verification / Alternative check:
Calling String.Compare(s1, s2) with default overloads also yields a positive value. Using StringComparer.OrdinalIgnoreCase (not used here) would yield equality (0), highlighting the effect of case sensitivity.



Why Other Options Are Wrong:
0 implies equality (not true due to case). -1 or -2 indicate s1 < s2, which contradicts the character comparison. 2 is not the typical printed value; while any positive value technically indicates 'greater than', standard examples show 1.



Common Pitfalls:
Assuming comparisons are case-insensitive by default or that the numeric values correspond to character code differences directly; CompareTo abstracts that away and only guarantees sign.



Final Answer:
1

More Questions from Strings

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion