像:
"Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"
如何获得“年龄”后的内容?我只想要数字。 (他的年龄)
答案 0 :(得分:5)
答案 1 :(得分:0)
您可以尝试使用以下概念的完整代码:
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);
}
强有力的做法是获得一些正则表达式:)尽管......
答案 2 :(得分:0)
假设您的年龄为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显示您的字符串值(如果找到)..
答案 3 :(得分:0)
实际上你有数据,可以很容易地表示为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"]);