"Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"
如何得到的是 「時代」 之後?我只想要數字。 (他的年齡)
"Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"
如何得到的是 「時代」 之後?我只想要數字。 (他的年齡)
你可以嘗試一個完整的代碼如下概念:
string strAge;
string myString = "Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student";
int posString = myString.IndexOf("Age: ");
if (posString >0)
{
strAge = myString.Substring(posString);
}
做的可靠的方法是讓一些正則表達式:)雖然...
@Abatishchev:神奇RegEx編輯器:)不錯! – bonCodigo
假設你有年齡在這種格式Age: value
string st = "Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student";
//Following Expression finds a match for a number value followed by `Age:`
System.Text.RegularExpressions.Match mt = System.Text.RegularExpressions.Regex.Match(st, @"Age\: \d+");
int age=0; string ans = "";
if(mt.ToString().Length>0)
{
ans = mt.ToString().Split(' ')[1]);
age = Convert.ToInt32(ans);
MessageBox.Show("Age = " + age);
}
else
MessageBox.Show("No Value found for age");
MessgeBox告訴你,你的字符串值(如果找到)..
其實你有數據,這些數據可以很容易地表示爲Dictionary<string, string>
類型的詞典:
var s = "Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student";
var dictionary = s.Split(new string[] { "---" }, StringSplitOptions.None)
.Select(x => x.Split(':'))
.ToDictionary(x => x[0].Trim(), x => x[1].Trim());
現在你可以從你的輸入字符串得到任何值:
string occupation = dictionary["Occupation"];
int age = Int32.Parse(dictionary["Age"]);
這是一個很好且可能的解決方案,但OP可能沒有準備好變量數據(從第三方獲取信息)。 –
字符串來自哪裏並沒有什麼區別。作爲最終結果,我們將有一個變量引用字符串數據:) –
聽起來像是正則表達式的工作:) – Mr47
使用String.IndexOf http://www.dotnetperls.com/indexof – user629926
http://stackoverflow.com/questions/4734116/c-sharp-find-and-extract-number-from-a-string在這裏找到靈感 – Pavenhimself