IamHe - 1 year ago 74
C# Question

# C# Extracting Ints from String and Comparing

Say for example I have a string of results from a few sport matches with each team represented by a letter. I want to focus on the Team 'A', and compare its scores with rest of the teams, to print out how many matches Team A has won, lost, drawn etc.... The sample string shown below.

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

I think the best way to do this would to extract all the scores of Team A and populate an array with them and do the same with the remaining scores. I have tried index to solve this, but keep getting stumped. Any ideas ?

Edit: Due to not posting attempts:

``````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());

}
``````

This populates the array with all digits so I am unsure of how to distinguish between them.

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

I then planned to use the indexs with substrings to extract the number and convert to an int, but this only works for the first and second occurrence and I have no idea how to get the other number values.

1. Split the string at the commas. This returns an array of strings.
2. Split each string in the array by whitespaces. This results in another array.
3. Extract the members of the array.

Here is a sample program.

``````  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);

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

}

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

Encapsulate the team / score in a separate class.

``````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;
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download