Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

String Methods Using Compare() I understand that Compare() means comparing 2 str

ID: 3823816 • Letter: S

Question

String Methods Using Compare()

I understand that Compare() means comparing 2 strings but I don't quite get the example below especially the part:

if(string.Compare(svalue, s)>0) // what is more than 0?? is it the characters in the string? if so, string s = "c#" should also be > 0 but when I try switching the if statement to if(string.Compare(s, svalue )>0) the output come out to be nothing?

string svalue = "c# programming";
string s = "c#";

if(string.Compare(svalue, s) > 0)
{
Console.WriteLine("sValue is lesco" + "graphically greater.");

}
Console.ReadLine();

Explanation / Answer

using System.IO;
using System;

class Program
{
static void Main()
{
string svalue = "c# programming";
string s = "c#";
if(string.Compare(svalue, s) > 0)
{
Console.WriteLine("sValue is lesco" + "graphically greater.");
}
Console.ReadLine();
}
}

When comparing strings, the comparison will be done between the relative characters of
both the strings:
And it will go like this:
for(int i = 0; i < min(firstStringlength, secondStringlength); i++)   //For each character in both the strings.
   if firstString[i] > secondString[i]
       firstString is lexicographically superior to second. //(firstString comes after secondString.)
   else if firstString[i] < secondString[i]
       secondString is lexicographically superior to first. //(secondString comes after firstString)
So, the above loop continues till same characters appear and as long as there are characters in both the strings.
Once the control is out of the loop,
if there are still characters in firstString:
   firstString is lexicographically superior to secondString. //(secondString is shorter, and will come before firstString.)
else if there are still characters in secondString:
   secondString is lexicographically superior to firstString. //(firstString is shorter, and will come before secondString.)  
else   //Which means no characters are left in both the strings, so they are considered same strings.
   the strings are the same.
  
So, hope you understood.
With this explanation we can say that svalue ("c# programming")   is lexicographically greater.