Pages

Saturday, April 27, 2013

C#: Reverse a Sentence using Stack

//declare a string to store the splitted characters
string str=null;
//declare a string array to store splitted words
string[] splitStr = null;
//declare a Stack with generic integer type
Stack<string> strArr = new Stack<string>();

public void StackReversal(string s)
{
//split the words using space delimiter
splitStr=s.Split(' ');


//Iterate each character in the sentence
foreach (char ch in s)
{

//Check if character is space or it reaches the last character in the sentence.   
if (ch.Equals(' ')||s[s.Length-1]==ch)
{

//Last character in the sentence is reached
if (s[s.Length - 1] == ch)
{
//join the characters to form a string
str = str + ch;
//add the string to stack
strArr.Push(str);
//exit the loop since end of sentence
break;
}

//if not end of sentence
strArr.Push(str);
// add string to stack
strArr.Push(" ");
//for joining the next string
str = null;
}
str = str + ch;
}
//get the stack count
int c = strArr.Count;
//loop through all items in stack and display in LIFO manner
for(int i=0; i<c;i++)
{
Console.Write(strArr.Pop());
}
Console.WriteLine();
}

//input string: "This is a sentence"
Output: sentence a is This


Monday, April 8, 2013

C#: Find the largest string in an array

//declare a string as empty
string large = "";
//function to find largest string
public void FindLargest(string[] str)
{
foreach (string s in str)//for each string in string array
{
//compare the length of each string in an array
  if (s.Length > large.Length)
  {
     large = s;
   }
}
Console.WriteLine(large);
}


//for input string array as "hi","hello"
Output: hello

Thursday, April 4, 2013

C#: Decimal to Binary Conversion

public string DecToBinConvert(string deci)
{
string output = null; //declare  variable to store result
int reminderVal = 0; //declare variable to store the remainder
        
if (!IsNum(deci))// check the value to convert is numeric
{
Console.WriteLine("Not numeric!!! Enter value between 0 and 9");
}
else
{
int number = int.Parse(deci);// if numeric parse string to integer type
while (number > 0)
{
reminderVal = number % 2;//if numeric value>0, get reminder value by mod 2
number = number / 2; //get quotient value
output = reminderVal.ToString() + output;
}
}
return output;
}

private bool IsNum(string numVal)// function to check a value is numeric
{
bool answer = false;
try
{
int temp = int.Parse(numVal);
answer = true; // returns true if numeric
}
catch (Exception ex)
{
answer = false;// returns false if not numeric
}
return answer;
}

//For input value  5 convert to binary,
Output: 1010
//For input value 9.2 convert to binary,
Output: Not numeric!!! Enter value between 0 and 9