Home > Software design >  ask a word from the console and print the index of each of its letters in the array
ask a word from the console and print the index of each of its letters in the array

Time:05-27

I need to write a C# program that creates an array containing all letters from the alphabet and ask for a word from the console and print the index of each of its letters in the array.(I don't ask for the whole code I just need help on what should I do , thanks)

this what I did;

using System.Collections.Generic;
using System.Linq;

namespace Letters
{
    public class letters
    {
        public static void Main(string[] args)
        {
            int l = 0;

            string[] letters = new string[26] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

            List<string> letterList = letters.ToList();

            Console.Write("Enter a word: ");
            string word = Console.ReadLine();

            while (l <= word.Length - 1)
            {
                Console.WriteLine(letterList.IndexOf(l)); l  ;
            }

            

        }
    }
}

but I need output like this

Enter a word: word

w:23 o:14 r:18 d:3

CodePudding user response:

close - heres a corrected and simplified version

    public static void Main(string[] args) {
        int l = 0;

        char[] letters = new char[26] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };



        Console.Write("Enter a word: ");
        string word = Console.ReadLine();

        foreach(char ch in word) {
            Console.WriteLine(Array.IndexOf(letters,ch)   1); 
        }



    }

and just for fun, here is a one liner

Console.WriteLine(word.Select(ch => $"{ch}:{(Char.ToLower(ch) - 'a')   1} ").Aggregate((a, b) => a   b));

using Flydogs calculation rather than a lookup table

  •  Tags:  
  • c#
  • Related