Advertisement
sylviapsh

Print Index Of Each Letter In A Word

Jan 11th, 2013
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. using System;
  2. class PrintIndexOfEachLetterInAWord
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program that creates an array containing all letters from the alphabet (A-Z). Read a word from the console and print the index of each of its letters in the array.
  7.  
  8.     //Read the input word from the console
  9.     string wordToSearch = Console.ReadLine(),
  10.            word = wordToSearch.ToLowerInvariant();//Make all letters small
  11.  
  12.     //Create the alphabet array (small letters)
  13.     char [] alphabet = new char [26];
  14.     alphabet[0] = 'a';
  15.     for (int i = 1; i < alphabet.Length; i++)
  16.     {
  17.       alphabet[i] = (char)(alphabet[i - 1] + 1);
  18.     }
  19.  
  20.     //Find each letter from the word with a binary search algorithm and output its index
  21.     foreach (char letter in word)
  22.     {
  23.       int startSearchIndex = 0,
  24.           endSearchIndex = alphabet.Length-1,
  25.           currentMiddle = 0;
  26.       bool foundFlag = false;
  27.  
  28.       while (startSearchIndex <= endSearchIndex)
  29.       {
  30.         currentMiddle = (startSearchIndex + endSearchIndex)/2;
  31.    
  32.         if (alphabet[currentMiddle] == letter)
  33.         {
  34.           Console.WriteLine("The index of the searched letter {0} is: {1}", letter, currentMiddle + 1); //the index is + 1 so that we get the number in the alphabet
  35.           foundFlag = true;
  36.           break;
  37.         }
  38.         else if (alphabet[currentMiddle] < letter)
  39.         {
  40.           startSearchIndex = currentMiddle + 1;
  41.         }
  42.         else
  43.         {
  44.           endSearchIndex = currentMiddle - 1;
  45.         }
  46.       }
  47.  
  48.     if (foundFlag == false)
  49.       {
  50.         Console.WriteLine("Symbol {0} not found in the array! Are you sure you've typed a word?", letter);
  51.       }
  52.     }
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement