-2

Looking for a way to split the following (poker hand) string: C 14 C 13 C 12 C 11 C 10 So that I can store the suits seperately to the card values, how can I seperate the characters and integers, new to c# and this is probably easy as hell, but please explain it to me in a newbie friendly way cheers :)

  • First link in google http://www.dotnetperls.com/split – acostela Sep 01 '15 at 13:16
  • It seems you are looking for the String's split method. check this out: https://msdn.microsoft.com/en-us/library/ms228388.aspx – Nikita Kurtin Sep 01 '15 at 13:17
  • also it's been asked a few times already. http://stackoverflow.com/questions/8928601/how-can-i-split-a-string-with-a-string-delimiter – Nikita Kurtin Sep 01 '15 at 13:19
  • 3
    Didn't you already ask this http://stackoverflow.com/questions/32316679/how-to-split-parts-of-string-into-2-different-arrays/32316803#32316803 – juharr Sep 01 '15 at 13:20

2 Answers2

0

follow below code

string str = "C 14 C 13 C 12 C 11 C 10";

string[] mixArray = str.Split(' ');

List<int> numbers = new List<int>();
List<string> characters = new List<string>();

for (int i = 0; i < mixArray.Length; i++)
{
    int tempInt;
    if (int.TryParse(mixArray[i], out tempInt))
        numbers.Add(tempInt);
    else
        characters.Add(mixArray[i]);
}
Darshan Faldu
  • 1,471
  • 2
  • 15
  • 32
0

I suggest you to have a more Object Oriented approach. First create your class 'Card' to store a single card inside

public class Card
{
    public int Value { get; set; }
    public string Suit { get; set; }
}

after this you can manage the string as follow

//Original string
string values = "C 14 C 13 C 12 C 11 C 10";
//this line will split your string in an array and will take out empty values if exists
var split = values.Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToArray(); ;

List<Card> cards = new List<Card>();
string card= string.Empty;

    for (int i = 0; i < split.Count() - 1; i += 2)
    {
        cards.Add(new Card() { Value = int.Parse(split[i + 1]), Suit = split[i] });
    }

After you have all the cards stored in a list that is more flexible than the array. I think could be better aproach.