首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 將字符串「a+bi」解析為複數的多種實現方法

     編輯:程式設計疑難解答

場景

需將形如 "123+5i"、"-10-3.5i" 的字符串解析為 System.Numerics.Complex 結構。

方法一:Split 分割(推薦,簡潔)

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"),可用正則或先替換 - 為 +- 再分割。

方法二:Substring + IndexOf(手動解析)

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("-", "+-")),代碼可讀性高且性能足夠;複雜格式採用正則。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved