2016-09-08 16 views
-4

舉例來說,我有一連串的結果來自與一個字母代表的每個團隊的幾場體育比賽。我想把注意力集中在A隊上,並將其得分與其他球隊進行比較,打印出A隊贏得,輸球,等等比賽的數量......下面的示例字符串。C#從字符串中提取Ints並比較

string results = " A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9"; 

我認爲做提取A隊的所有得分和填充他們的數組,並做相同的剩餘分數的最佳途徑此會。我嘗試過索引來解決這個問題,但是一直在困擾。有任何想法嗎 ?

編輯:由於沒有張貼的嘗試:

char[] tobeconverted = results.Where(Char.IsDigit).ToArray(); 
     int[] sequence = new int[10]; 

     for (int i = 0; i < tobeconverted.Length; i++) 
     { 
      sequence[i] = Convert.ToInt32(tobeconverted[i].ToString()); 

     } 

這與填充所有數字數組,所以我不確定如何區分它們。

 string teamA = "A "; 
     int indexOfNextOccurance = results.IndexOf(teamA, results.IndexOf(teamA) + 1); 

然後我打算用指數法與子提取次數和轉換爲int,但這僅適用於第一和第二次出現,我不知道如何讓其他數值。

+1

當你問社區解決,你是無法做到的一個問題,它是更好,如果你發佈你的企圖,所以我們可以看到,這是不是一個_give我格蘭codez_各種問題 – Steve

+0

的同時,發佈你的企圖阻止我們提出你已經試過的東西,並放棄不可行的事情。 – Tim

+4

8條數據如何粘到一個字符串中? – Plutonix

回答

0
  1. 在逗號分隔字符串。這將返回一個字符串數組。
  2. 用空格分隔數組中的每個字符串。這導致另一個陣列。
  3. 提取數組的成員。

這裏是一個示例程序。

class Program 
    { 
    static void Main(string[] args) 
    { 

     string results = " A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9"; 

     string[] matches = results.Trim().Split(','); 

     List<Match> sportResults = new List<Match>(); 
     foreach (string match in matches) 
     { 
     string[] parts = match.Trim().Split(null); 

     sportResults.Add(new Match() { 
      Team1 = parts[0], Score1 = int.Parse(parts[1]), 
      Team2 = parts[2], Score2 = int.Parse(parts[3])}); 

     } 

     sportResults.ForEach(a => Console.WriteLine(a)); 
    } 
    } 

將團隊/分數封裝在單獨的課程中。

class Match 
    { 
    public string Team1 { get; set; } 
    public string Team2 { get; set; } 

    public int Score1 { get; set; } 
    public int Score2 { get; set; } 

    public override string ToString() 
    { 
     return "Team " + Team1 + " " + Score1 + " VS " + Team2 + " " + Score2; 
    } 
    } 
+0

謝謝,非常感謝 – IamHe

0
string results = "A 1 B 0, A 2 C 4, A 1 D 8, A 5 E 9"; 
     List<int> teamAScores = new List<int>(); 
     List<int> otherTeamScores = new List<int>(); 
     foreach(string scoreSet in results.Split(',')) 
     { 
      scoreSet.Replace(" ", ""); 
      int teamA = -1; 
      int teamX = -1; 
      int.TryParse(scoreSet.Substring(1, 1), out teamA); 
      int.TryParse(scoreSet.Substring(3, 1), out teamX); 
      if (teamA > -1 && teamX > -1) 
      { 
       teamAScores.Add(teamA); 
       otherTeamScores.Add(teamX); 
      } 
     } 

您現在有一個列表,其中每個遊戲的分數都與索引相匹配。

+0

謝謝,這有助於 – IamHe

+0

不用擔心 - 保重! –