-1

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

derloopkat
  • 6,232
  • 16
  • 38
  • 45
Kmel
  • 15
  • 3
  • When asking for help on SO, you have to show your own effort at solving the problem. Just dumping your homework in a question and expecting help is not how we help here at SO. – Maverik Apr 13 '16 at 15:50

2 Answers2

4

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:

...--

derloopkat
  • 6,232
  • 16
  • 38
  • 45
0

\d+ is the regex for an integer number. So

//System.Text.RegularExpressions.Regex

resultString = Regex.Match(subjectString, @"\d+").Value;
returns a string containing the first occurrence of a number in subjectString.

Int32.Parse(resultString) will then give you the number.

From Find and extract a number from a string

Community
  • 1
  • 1
Antoine
  • 312
  • 1
  • 5
  • 18