I'm new to programming in C# and now I've got a question about one of my projects. I have to get the first digit in a string and then convert it to Morse code.
Here's an example:
Hello123 --> I need "1"
Bye45 --> I need "4"
How do I get this? Thanks in advance
Using Linq, first character is:
char firstDigit = this.Message.FirstOrDefault(c => char.IsDigit(c));
Then, create a Dictionary for converting a digit into Morse code.
class Program
{
static void Main(string[] args)
{
const string text = "abcde321x zz";
var morse = new Morse(text);
Console.WriteLine(morse.Code);
}
}
class Morse
{
private static Dictionary<char, string> Codes = new Dictionary<char, string>()
{
{'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
{'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."},
{'9', "----."}, {'0', "-----"}
};
private string Message;
public string Code
{
get
{
char firstDigit = this.Message.FirstOrDefault(c => char.IsDigit(c));
return Codes.ContainsKey(firstDigit) ? Codes[firstDigit] : string.Empty;
}
}
public Morse(string message)
{
this.Message = message;
}
}
Output is:
...--