Archive for the ‘ String ’ Category

Write a Program to Print String in Triangular Format

Today we will write a program for printing a given string’s in triangle.

For Example

input : Independence

Output

image

Code

For First Image

        public static void PrintStringInTriangle(this string input)
        {
            int length = input.Length;

            for (int i = 0; i < length; i++)
            {
                for (int spaceCounter =0; spaceCounter <=length-i; spaceCounter++)
                {
                    Console.Write(" ");
                }
                for (int charCounter = 0; charCounter <=i; charCounter++)
                {
                    Console.Write(input[charCounter]);
                    Console.Write(" ");
                }
                Console.WriteLine("");
            }


        }

For Second Image

        public static void PrintStringInLeftTriangle(this string input)
        {
            int length = input.Length;

            for (int i = 0; i < length; i++)
            {
                for (int spaceCounter = 0; spaceCounter <= length - i; spaceCounter++)
                {
                    Console.Write(" ");
                }
                for (int charCounter = 0; charCounter <= i; charCounter++)
                {
                    Console.Write(input[charCounter]);
                     
                }
                Console.WriteLine("");
            }


        }

For Third Image

        public static void PrintStringInRightTriangle(this string input)
        {
            int length = input.Length;

            for (int i = 0; i < length; i++)
            {
                for (int spaceCounter = 0; spaceCounter <= length; spaceCounter++)
                {
                    Console.Write(" ");
                }
                for (int charCounter = 0; charCounter <= i; charCounter++)
                {
                    Console.Write(input[charCounter]);

                }
                Console.WriteLine("");
            }


        }

Find Maximum Occurrence of a Character in a Given String

        public static char MaximumOccurringCharacter(this string input)
        {
           
SortedDictionary<char, int> charDict = new SortedDictionary<char, int
>();
           
int
length = input.Length;

            for (int i = 0; i < length; i++)
            {
               
if
(charDict.ContainsKey(input[i]))
                {
                    charDict[input[i]]++;
                }
               
else
               
{
                    charDict.Add(input[i], 1);
                }
            }

            var max = charDict.Values.Max();
           
var
relevantKeys = charDict.Where(pair => max.Equals(pair.Value))
                .Select(pair => pair.Key).First();
           
return
relevantKeys;

        }

Test Case

Console.WriteLine("Max occur char in string test is : " + "test".MaximumOccurringCharacter());

Console.WriteLine("Max occur char in string maximum is : " + "maximum".MaximumOccurringCharacter());

Console.WriteLine("Max occur char in string MaximumOccurringCharacter is : " + "MaximumOccurringCharacter".MaximumOccurringCharacter());

Output

Max occur char in string test is : t
Max occur char in string maximum is : m
Max occur char in string MaximumOccurringCharacter is : r

Write code to check a String is palindrome or not

A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction.

public static bool IsPalindrome(this string input)
     {
         bool result = true;
         input = input.Trim();
         try
         {

             if (string.IsNullOrEmpty(input))
             {
                 return result = false;
             }

             var inputArray = input.ToCharArray();

             if (inputArray.Length == 1)
             {
                 return result = true;
             }

             int length = inputArray.Length – 1;

             for (int i = 0; i <= length / 2; i++)
             {
                 if (inputArray[i] != inputArray[length - i])
                 {
                     return result == false;
                 }
             }
         }
         catch (Exception)
         {

             result = false;
         }
         return result;

     }
Test Case

string s = "";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "AJAY";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "ABBA";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "ABBa";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "palindrome";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));

Output:

String  IsPalindrome False
String AJAY IsPalindrome False
String ABBA IsPalindrome True
String ABBa IsPalindrome False
String palindrome IsPalindrome False

Reverse the word in a string

For reversing the word in a string I used following algorithm

  1. Traverse the string and push the characters in stack, until we get space
  2. When space is encountered, pop the element from stack and enqueue in queue
  3. enqueue the spaces in queue
  4. once the traverse is complete add the last word in queue

Stack is used to reverse the characters and queue is used to maintain the order of characters

 

   public static void ReverseWordOfString(string s)
    {
      if (string.IsNullOrEmpty(s))
      {
        Console.WriteLine("String is empty");
        return;
      }

      Stack<char> charStack = new Stack<char>();
      var charArray = s.ToCharArray();
      int length = charArray.Length;
      Queue<char> result = new Queue<char>();
      Console.WriteLine("input string : {0}", s);
      for (int i = 0; i < length; i++)
      {
        if (charArray[i] != ' ')
        {
          charStack.Push(charArray[i]);
        }
        else
        {
          while (charStack.Count > 0)
          {
            result.Enqueue(charStack.Pop());
          }
          result.Enqueue(' ');
        }
      }
      while (charStack.Count > 0)
      {
        result.Enqueue(charStack.Pop());

      }

      Console.Write("String After reversing the words : ");
      Console.Write(result.ToArray());
      Console.WriteLine();

    }

RIL : Given AAABBGFF should get an output 3{A} 2{B}1{G}2{F}

Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs: for example, simple graphic images such as icons, line drawings, and animations. It is not useful with files that don’t have many runs as it could greatly increase the file size.

  /// <summary>
        /// Given AAABBGFF should get an output 3{A} 2{B}1{G}2{F}
        /// http://en.wikipedia.org/wiki/Run-length_encoding
        /// </summary>
        /// <param name="input"></param>
        public static void RIL(string input)
        {
            Console.Write(input + " : " );
            StringBuilder output = new StringBuilder();
            int charCount = 0;
            var inputChars = input.ToCharArray();
            char currentChar, nextChar;
            currentChar = nextChar = inputChars[0];

            for (int i = 0; i < inputChars.Length; i++)
            {
                currentChar = inputChars[i];
                if (i + 1 < inputChars.Length)
                {
                   
                    nextChar = inputChars[i + 1];
                }
                if (currentChar  != nextChar )
                {

                    output.Append(charCount + 1);
                    output.Append("{");
                    output.Append(currentChar);
                    output.Append("}");
                    charCount = 0;
                
                }
                else {
                    charCount++;
                }
            }
            output.Append(charCount );
            output.Append("{");
            output.Append(currentChar);
            output.Append("}");
            
            Console.Write(output.ToString());
            Console.WriteLine();

        }

Test Cases

  1. AAABBGFF : 3{A}2{B}1{G}2{F}
  2. WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWW WWWWWWBWWWWWWWWWWWWWW : 12{W}1{B}12{W}3{B}24{W}1{B}14{W}
  3. AAABBGGGGGGGGFFXXXXXXTTTTTyyyyyyvvvvv : 3{A}2{B}8{G}2{F}6{X}5{T}6{y}5{v}
  4. AAAABBCCCCCCCBBCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD :

    4{A}2{B}7{C}2{B}4{C}38{D}