Tuesday 15 October 2013

Count words and reverse operation in Char Array

In interview sometimes asked logical question. One of is here.
  • Get the count of word in given char array in c#. So here you go..
char[] arr = "My name is ABC XYZ.".ToCharArray();
               
 string str = "";
 ArrayList lst = new ArrayList();
 foreach (var item in arr)
  {
  if (item.ToString() == " " || item.ToString() == ".")
   {
       lst.Add(str);
       str = "";
   }
  else
  {
   str += item.ToString();
  }

 }
 Response.Write(lst.Count);

Output :  5
  • Get the reverse order of char array
 //For reverse array
 lst.Reverse();
 var mystr = "";
 foreach (var item in lst)
 {
  mystr += item + " ";
 }
 Response.Write("Count : " + lst.Count + " Reverse : " + mystr);

Output : XYZ ABC is name My
  • Get the reverse order of char array with single string
 //Reverse string
 char[] abc = "HiralSavaria".ToCharArray();
 Array.Reverse(abc);
 Response.Write("
" + new string(abc));

Output : airavaSlariH

No comments:

Post a Comment