c#拆分字符串的输入

时间:2014-01-17 17:45:11

标签: c# split

我最近在课堂上从c ++转到c#,我看了很多,但没有找到太多。我有以下问题。我应该能够让用户添加一个复杂的数字。例如

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

我知道我可以分开 - 符号,但有一些问题,如

4 + 3.2i或甚至只是一个数字3.2i。

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

2 个答案:

答案 0 :(得分: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);

        }
    }
}

答案 1 :(得分: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() );
        }
    }
}

结果: