Click here to Skip to main content
15,353,547 members
Home / Discussions / C#
   

C#

 
AnswerRe: Invalid expression term 'uint' Pin
OriginalGriff15-May-22 0:09
mveOriginalGriff15-May-22 0:09 
GeneralRe: Invalid expression term 'uint' Pin
mbah obiora15-May-22 1:54
Membermbah obiora15-May-22 1:54 
GeneralRe: Invalid expression term 'uint' Pin
OriginalGriff15-May-22 2:05
mveOriginalGriff15-May-22 2:05 
QuestionParse complex numbers from string Pin
Member 1563407112-May-22 8:28
MemberMember 1563407112-May-22 8:28 
AnswerRe: Parse complex numbers from string Pin
OriginalGriff12-May-22 9:42
mveOriginalGriff12-May-22 9:42 
AnswerRe: Parse complex numbers from string Pin
jsc4213-May-22 0:13
professionaljsc4213-May-22 0:13 
GeneralRe: Parse complex numbers from string Pin
Member 1563407116-May-22 8:02
MemberMember 1563407116-May-22 8:02 
GeneralRe: Parse complex numbers from string Pin
jsc4217-May-22 3:19
professionaljsc4217-May-22 3:19 
There doesn't seem to be a Point.Parse() / Point.TryParse() so that did not get very far!
Normally, we don't give working answers, just rough pointers. However, I had wanted to create a Point.Parse() / Point.TryParse() for a different project, but had not got around to it; so this was a good excuse to write one Smile | :) .

This version allows (x-yi) and (x-yb) as well as your formats plus you can use (x, y) [with a space after the real/imaginary separator] to disambigute for cultures that use ',' as a decimal point.

My basic functions look like:
C#
public static class Complex2
 {
     public static Complex ComplexParse(string text)   // (x, y) or (x+yi) or (x+yj) or (x-yi) or (x-yj)
     {
         string[] parts;
         string parsedText = text.Trim();
         if (parsedText.StartsWith("(") && parsedText.EndsWith(")"))
         {
             parsedText = parsedText.Substring(1, parsedText.Length - 2).Trim(); // Drop parentheses
             if (parsedText.Contains("+") && (parsedText.EndsWith("i") || parsedText.EndsWith("j")))
             {
                 parts = parsedText.Split('+');
                 if (parts.Length == 2)
                     return
                         new Complex(
                             real: double.Parse(parts[0].Trim()),
                             imaginary: double.Parse(parts[1].Substring(0, parts[1].Length - 1).Trim())
                             );

                 throw new ArgumentException("Complex number format not recognised (multiple '+' chars)");
             }
             else if (parsedText.Substring(1).Contains("-") && (parsedText.EndsWith("i") || parsedText.EndsWith("j")))   // (x-yi) or (x-yj) // Beware of (-x-yi) or (-x-yj)
             {
                 parts = parsedText.Substring(1).Split('-');
                 if (parts.Length == 2)
                     return
                         new Complex(
                             real: double.Parse(parsedText.Substring(0, 1) + parts[0].Trim()),
                             imaginary: -double.Parse(parts[1].Substring(0, parts[1].Length - 1).Trim())
                             );

                 throw new ArgumentException("Complex number format not recognised (multiple '+' chars)");
             }
             else if (parsedText.Contains(","))  // Hopefully in the form x, y
             {
                 parts = parsedText.Split(',');
                 if (parts.Length == 2)
                     return
                         new Complex(
                             real: Double.Parse(parts[0].Trim()),
                             imaginary: Double.Parse(parts[1].Trim())
                             );

                 // Too many commas. Can only diambiguate if one is followed by a space
                 int ix = parsedText.IndexOf(", ");
                 if (ix < 1)     // ", " not found or there is an empty real part
                     throw new ArgumentException("Complex number format not recognised (ambiguous use of commas)");

                 return
                     new Complex(
                         real: double.Parse(parsedText.Substring(0, ix).Trim()),
                         imaginary: double.Parse(parsedText.Substring(ix + 1).Trim())
                         );
             }
             else
                 throw new ArgumentException("Complex number format not recognised");
         }
         else
             throw new ArgumentException("Complex number not enclosed in parentheses");
     }

     public static bool ComplexTryParse(string text, out Complex ComplexOut)
     {
         try
         {
             ComplexOut = ComplexParse(text);
             return true;
         }
         catch (Exception)
         {
             ComplexOut = new Complex(0.0, 0.0);
             return false;
         }
     }
 }

and to use as extension methods for string:
C#
public static class StringExtensions
 {
     public static Complex ComplexParse(this string fromText) =>
         Complex2.ComplexParse(fromText);

     public static bool ComplexTryParse(this string fromText, out Complex result) =>
         Complex2.ComplexTryParse(fromText, out result);
 }

Sample testing:
C#
class Program
{
    static void Main(string[] args)
    {
        // Should pass
        TryComplex("(1.0,0.5)");
        TryComplex("(1.1+0.55i)");
        TryComplex(" ( 1.023 + 0.512 j ) ");
        TryComplex("(0, -1)");
        TryComplex("(0-1i)");
        TryComplex("(-10-2j)");
        TryComplex("(-10,-3)");
        TryComplex(" ( 1.8-1i ) ");
        TryComplex(" ( 1.9+1i ) ");

        // Culture specific
        TryComplex("(1,4, 2,5)");   // (14, 25) in UK (extra ','s ignored)

        // Should fail
        TryComplex(" ( 1,1i ) ");
        TryComplex("(1,4,2,5)");
        TryComplex(" ( 1.023 + 0.512 + j ) ");
        TryComplex(" ( 1.023, 0.512 j ) ");
        TryComplex(" ( 1.023i 0.512 j ) ");

        Console.ReadKey();  // Wait to close the console window
    }

    static void TryComplex(string text)
    {
        Console.Write($"Trying {text}: ");

        try
        {
            Complex result = text.ComplexParse();
            Console.WriteLine($"({result.Real}, {result.Imaginary})");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"*** Failed: {ex.Message} ***");
        }
    }
}

Note: For these to work, I have used
C#
using System.Numerics;
using static ComplexParser.Complex2;    // Where ComplexParser is my outer namespace that contains the static class Complex2

to save having to use namespace prefixes


Hope this is of some use.
GeneralRe: Parse complex numbers from string Pin
Richard Deeming17-May-22 3:26
mveRichard Deeming17-May-22 3:26 
GeneralRe: Parse complex numbers from string Pin
jsc4217-May-22 5:05
professionaljsc4217-May-22 5:05 
GeneralRe: Parse complex numbers from string Pin
jsc4217-May-22 22:16
professionaljsc4217-May-22 22:16 
Question"interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff11-May-22 1:25
mveBillWoodruff11-May-22 1:25 
AnswerRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
OriginalGriff11-May-22 2:15
mveOriginalGriff11-May-22 2:15 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff11-May-22 3:29
mveBillWoodruff11-May-22 3:29 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
Richard Deeming11-May-22 6:16
mveRichard Deeming11-May-22 6:16 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff11-May-22 17:20
mveBillWoodruff11-May-22 17:20 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
Richard Deeming11-May-22 21:37
mveRichard Deeming11-May-22 21:37 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff11-May-22 23:33
mveBillWoodruff11-May-22 23:33 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
Richard Deeming12-May-22 0:19
mveRichard Deeming12-May-22 0:19 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff12-May-22 1:12
mveBillWoodruff12-May-22 1:12 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
Richard Deeming12-May-22 2:18
mveRichard Deeming12-May-22 2:18 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff12-May-22 2:32
mveBillWoodruff12-May-22 2:32 
AnswerRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
Richard MacCutchan11-May-22 3:19
mveRichard MacCutchan11-May-22 3:19 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
BillWoodruff11-May-22 3:50
mveBillWoodruff11-May-22 3:50 
GeneralRe: "interface hack" to make private nested class instances available to outer class methods ? Pin
harold aptroot11-May-22 10:28
Memberharold aptroot11-May-22 10:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.