像:
"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);
}
稳健的做法是得到一些正则表达式:)虽然......
假设你有这种格式的年龄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");
MessageBox 向您展示您的字符串值(如果找到)..
实际上你有数据,可以很容易地表示为类型的字典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"]);