CopyPastehas never been so tasty!

Compare string with char array in c#

by anonymous

  • 0
  • 0
  • 0
147 views

Compare string with char array in c#

String ArrayString Arrays are used to store more than one string. We create and declare string arrays like that:string[] arr1 = new string[] { "one", "two", "three" };  Char ArrayA char array stores string data in sequence. For example if we take an array that can store up to 10 char type elements. It will be represented asString s = “hello”

h

e

l

l

o

 

 

 

 

 

Comparison of String and char[]The following code will demonstrate the comparison of string and char array. If the char[] value is smaller than the string , the return value will be 1 if vice versa then the return value will be -1 otherwise the default value 0 would be return.Code 

class Program

    {

static void Main(string[] args)

        {

 char[] m = { '0', '1', '2' };

 Console.WriteLine(Program.Compare(m, "123"));

Console.ReadLine();

        }

 public static int Compare(char[] c, String s)

        {

char[] a = s.ToCharArray();

for (int i = 0; i < a.Length; i++)

            {

if (c[i] < a[i])

return 1;

if (c[i] > a[i])

return -1;

            }

return 0;

        }

    }

  

In the given code the return value is 1 then char[] value is smaller than the string.

Add A Comment: