需將形如 "123+5i"、"-10-3.5i" 的字符串解析為 System.Numerics.Complex 結構。
string s = "123+5i";
double real = double.Parse(s.Split('+')[0]);
double imag = double.Parse(s.Split('+')[1].Split('i')[0]);
Complex c = new Complex(real, imag);
注意:需處理負號情況(如 "-10-3.5i"),可用正則或先替換 - 為 +- 再分割。
string s = "123+5i";
int plusIndex = s.IndexOf('+');
double real = double.Parse(s.Substring(0, plusIndex));
double imag = double.Parse(s.Substring(plusIndex + 1, s.Length - plusIndex - 2)); // 去掉末尾 'i'
Complex c = new Complex(real, imag);
邊界處理較繁瑣,易出現索引越界。
var match = Regex.Match(s, @"^([+-]?\d*\.?\d+)([+-]\d*\.?\d+)i$");
if (match.Success) {
double real = double.Parse(match.Groups[1].Value);
double imag = double.Parse(match.Groups[2].Value);
Complex c = new Complex(real, imag);
}
可同時匹配 a+bi、a-bi、-a+bi 等格式。
優先使用 方法一 配合簡單預處理(如 s = s.Replace("-", "+-")),代碼可讀性高且性能足夠;複雜格式採用正則。