Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class PrintIndexOfEachLetterInAWord
- {
- static void Main()
- {
- //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.
- //Read the input word from the console
- string wordToSearch = Console.ReadLine(),
- word = wordToSearch.ToLowerInvariant();//Make all letters small
- //Create the alphabet array (small letters)
- char [] alphabet = new char [26];
- alphabet[0] = 'a';
- for (int i = 1; i < alphabet.Length; i++)
- {
- alphabet[i] = (char)(alphabet[i - 1] + 1);
- }
- //Find each letter from the word with a binary search algorithm and output its index
- foreach (char letter in word)
- {
- int startSearchIndex = 0,
- endSearchIndex = alphabet.Length-1,
- currentMiddle = 0;
- bool foundFlag = false;
- while (startSearchIndex <= endSearchIndex)
- {
- currentMiddle = (startSearchIndex + endSearchIndex)/2;
- if (alphabet[currentMiddle] == letter)
- {
- 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
- foundFlag = true;
- break;
- }
- else if (alphabet[currentMiddle] < letter)
- {
- startSearchIndex = currentMiddle + 1;
- }
- else
- {
- endSearchIndex = currentMiddle - 1;
- }
- }
- if (foundFlag == false)
- {
- Console.WriteLine("Symbol {0} not found in the array! Are you sure you've typed a word?", letter);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement