2013-05-28 53 views
1

對於C#我很新,我想做一個cardgame。我所擁有的是卡片(字符串)列表,其名稱爲c6, s3, h11, d13,其中character represents the colournumber represents the value。當按下按鈕時,程序從列表中隨機選擇一個字符串並將其顯示在文本框中。從那裏開始,遊戲的重點就是猜測下一張隨機卡的數值是否會比前一張卡的數值更高或值更低。在C#中將字符串轉換爲int#

我想要做的是從文本框中取出字符串,並將它變成一個int,以便我可以比較以前的卡與新的卡的值。唯一的問題是我如何擺脫c6中的c,所以我可以使用parse來轉換它。

這是我的代碼。

public partial class MainWindow : Window 
{ 
    static Random rndmlist = new Random(); 
    Random rndm = new Random(); 
    List<string> deck = new List<string>(); 
    int score = 0; 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void test_Click(object sender, RoutedEventArgs e) 
    { 
     //disregard this 
     foreach (string j in deck) 
     { 
      testbox.Text += j + ", "; 
     } 
    } 

    private void btnstart_Click(object sender, RoutedEventArgs e) 
    { 
     //this is where i add all the cards to the list 
     for (int i = 1; i <= 13;) 
     { 
      deck.Add("c" + i); 
      i++; 
     } 
     for (int i = 1; i <= 13;) 
     { 
      deck.Add("s" + i); 
      i++; 
     } 
     for (int i = 1; i <= 13;) 
     { 
      deck.Add("h" + i); 
      i++; 
     } 
     for (int i = 1; i <= 13;) 
     { 
      deck.Add("d" + i); 
      i++; 
     } 
    } 

    private void btnbegin_Click(object sender, RoutedEventArgs e) 
    { 
     //this is where i take a random card from the list and display it in textBox2 
     int r = rndmlist.Next(deck.Count); 
     textBox2.Text = ((string)deck[r]); 

     //disregard this 
     testbox.Text += ((string)deck[r]) + ", "; 
     deck.Remove((string)deck[r]); 
    } 

    private void btnhigh_Click(object sender, RoutedEventArgs e) 
    { 
     //this is where i want to compare the cards. 
    } 
} 

非常感謝您閱讀本文。 (:

+2

' int.Parse(str.Substring(1))' –

+11

如果你用一個'struct Card'模擬卡片,它的'Suit'和'Value'字段映射到枚舉而不是啞字符串,它可能會更好。 – Jon

+1

使用mystring.Substring(1); – rags

回答

1

試試這個,

string SubString = MyString.Substring(1); 

但如果字符串是空的照顧,這是一個錯誤的情況下

+0

我決定和這個一起去,因爲它很簡單。感謝所有的幫助:D –

+0

不客氣;)! – Leep

0

您可以使用正則表達式替換所有字母字符,例如

string result = Regex.Replace(myString, @"[a-zA-Z\s]+", string.Empty); 
1

假設數字前總會有一個(且只有一個)字符,您可以簡單地這樣做:

string numberAsString = "c2".Substring(1); 

並做出對的int

int number = Int32.Parse(numberAsString); 
0
string str = "c12"; 
var noChars = str.SubString(1); // take a new string from index 1 
var number = Int32.Parse(noChars); 
5

我最好創建一個類Card,它代表了一張名片,2個屬性:ColorNumber和實現的方法Card.ParseFromString()