C#分割字符串输入

3

我最近在课程中从c++转到了c#,但是我搜索了很多地方都没有找到太多相关信息。我遇到了以下问题:我应该让用户添加一个复数。例如:

-3.2 - 4.1i 我想要将其拆分并存储为(-3.2) - (4.1i)

我知道可以在负号处进行拆分,但是还存在一些问题,比如

4 + 3.2i 或者只有一个数字3.2i。

任何帮助或见解都将不胜感激。


3
听起来你需要的是正则表达式。 - Mike Christensen
谢谢@Default和所有人,我想我会尝试解析到空格。但是我可以看到-3.2-4.1i可能会有问题。 - Derked
@Derked 好的,那么我们回到正则表达式了。在我脑海中,它可能是类似于 [0-9]?[.][0-9]?i? 的东西。 - default
1
针对@Default关于Complex的建议 - 结果发现System.Numerics.Complex没有任何类型的Parse方法 - 因此适用于存储,但无法用于解析。 - Alexei Levenkov
那么1e-3+4.2e-2i或其他浮点数呢?还有5i-1。看起来你需要一个相当强大的表达式解析器。 - John Alexiou
显示剩余4条评论
2个回答

1

通过使用正则表达式匹配所有有效的输入,然后进行组装即可。正则表达式的工作原理是:

  • [0-9]+ 匹配 0-n 个数字
  • [.]? 匹配 0 或 1 个点
  • [0-9]+ 匹配 0-n 个数字
  • i? 匹配 0 或 1 个 "i"
  • | 或者
  • [+-*/]? 匹配 0 或 1 个运算符 +、-、* 或 /

.

public static void ParseComplex(string input)
{
    char[] operators = new[] { '+', '-', '*', '/' };

    Regex regex = new Regex("[0-9]+[.]?[0-9]+i?|[+-/*]?");
    foreach (Match match in regex.Matches(input))
    {
        if (string.IsNullOrEmpty(match.Value))
            continue;

        if (operators.Contains(match.Value[0]))
        {
            Console.WriteLine("operator {0}", match.Value[0]);
            continue;
        }

        if (match.Value.EndsWith("i"))
        {
            Console.WriteLine("imaginary part {0}", match.Value);
            continue;

        }
        else
        {
            Console.WriteLine("real part {0}", match.Value);

        }
    }
}

0

这仍然存在许多缺陷和可能出现问题的方式,但它有点工作。

struct Complex
{
    float re, im;

    public static Complex Parse(string text)
    {
        text=text.Replace(" ", string.Empty); //trim spaces
        float re=0, im=0;
        int i_index=text.IndexOf('i');
        if(i_index>=0) //if no 'i' is present process as real only
        {
            text=text.Substring(0, i_index); //ignore all after i

            int i=0;
            //find start of digits
            while(i<text.Length&&(text[i]=='+'||text[i]=='-'))
            {
                i++;
            }
            //find end of digits
            while(i<text.Length&&(char.IsNumber(text, i)|| text.Substring(i).StartsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)))
            {
                i++;
            }
            // parse real (first) portion
            float.TryParse(text.Substring(0, i), out re);
            // had 'i' but no numbers
            if(text.Length==0)
            {
                im=1;
            }
            else
            {
                //parse remaining value as imaginary
                text=text.Substring(i+1);
                float.TryParse(text, out im);
            }
        }
        else
        {
            float.TryParse(text, out re);
        }
        // Build complex number
        return new Complex() { re=re, im=im };
    }
    public override string ToString()
    {
        return string.Format("({0},{1})", re, im);
    }
}
class Program
{
    static void Main(string[] args)
    {
        var test=new[] { "1", "i", "5+2i", "-5+2i", "+5-2i", "0.23+0.72i" };

        for(int i=0; i<test.Length; i++)
        {
            Debug.Print( Complex.Parse(test[i]).ToString() );
        }
    }
}

结果:

(1,0)
(0,1)
(5,2)
(-5,2)
(5,2)
(0.23,0.72)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接