2013-05-03 68 views
1

我正在處理一個簡單的Windows窗體應用程序,用戶輸入帶分隔符的字符串,然後解析字符串,並只將變量從字符串中取出。 因此,例如,如果用戶輸入:C# - 輸入字符串的格式不正確

2X + 5Y + z^3 

我提取值2,5和3從「方程」與簡單地添加在一起。

這是我如何從字符串中獲取整數值。

int thirdValue 
string temp; 
temp = Regex.Match(variables[3], @"\d+").Value 
thirdValue = int.Parse(temp); 

variables只是我用來存儲字符串解析後的字符串數組。

不過,我得到以下錯誤,當我運行應用程序:

輸入字符串的不正確的格式

+0

請在'temp'內打印出值。這可能有點啓發你。 – christopher 2013-05-03 16:17:52

+2

這甚至不會編譯 - 你能顯示你的真實代碼嗎? (Match.Value是一個'string',所以你不能分配給'int temp'等等) – 2013-05-03 16:21:01

+0

究竟如何指定regex匹配到int? – PSL 2013-05-03 16:21:26

回答

0

你可以改變字符串的字符數組,檢查其一個數字並數起來。

 string temp = textBox1.Text; 
     char[] arra = temp.ToCharArray(); 
     int total = 0; 
     foreach (char t in arra) 
     { 
      if (char.IsDigit(t)) 
      { 
       total += int.Parse(t + ""); 
      } 
     } 
     textBox1.Text = total.ToString(); 
+0

Buggy在數字大於9的情況下:「2X + 65Y + z^3」 – astef 2013-05-03 20:20:51

+0

雖然我們需要更好地解釋任務 – astef 2013-05-03 20:22:18

0

這應該解決您的問題:

string temp; 
temp = Regex.Matches(textBox1.Text, @"\d+", RegexOptions.IgnoreCase)[2].Value; 
int thirdValue = int.Parse(temp); 
2

我更喜歡簡單的輕量級解決方案,而Regex

static class Program 
{ 
    static void Main() 
    { 
     Console.WriteLine("2X + 65Y + z^3".GetNumbersFromString().Sum()); 
     Console.ReadLine(); 
    } 

    static IEnumerable<int> GetNumbersFromString(this string input) 
    { 
     StringBuilder number = new StringBuilder(); 
     foreach (char ch in input) 
     { 
      if (char.IsDigit(ch)) 
       number.Append(ch);     
      else if (number.Length > 0) 
      { 
       yield return int.Parse(number.ToString()); 
       number.Clear(); 
      } 
     } 
     yield return int.Parse(number.ToString()); 
    } 
} 
0

爲什麼我呻吟,大家對這個問題,並標記下來呢?解釋發生的事情是非常容易的,並且提問者正如他所說的那樣正確地說出來。沒有任何問題。

Regex.Match(variables[3], @"\d+").Value 

拋出一個Input string was not in a correct format..出現FormatException如果字符串(這裏是variables[3])不包含任何數字。 當它作爲服務運行時,它也可以在數組的內存堆棧中訪問variables[3]。我懷疑這是一個錯誤錯誤是.Value爲空並且.Match失敗。

現在很坦白地說,如果你問我,這是一個僞裝成bug的功能,但它的意思是設計功能。正確的方法(恕我直言)已完成此方法將返回一個空白字符串。但他們不會拋出FormatException。去搞清楚。正是由於這個原因,你被astef建議甚至不打擾正則表達式,因爲它拋出異常並且令人困惑。但他也被打倒了!

繞着它的方式是使用如果這仍然不會爲你工作,你不能使用正則表達式這一點,他們也取得了

if (Regex.IsMatch(variables[3], @"\d+")){ 
    temp = Regex.Match(variables[3], @"\d+").Value 
} 

這個簡單的另一種方法。我在c# service看到這不起作用,並引發不正確的錯誤。所以我不得不停止使用正則表達式