1

Like:

"Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"

How to get what is after "Age"? I would only like the numbers. (his age)

J. Steen
  • 15,470
  • 15
  • 56
  • 63
user1708328
  • 51
  • 1
  • 2
  • 6

4 Answers4

5

Use RegEx:

^.+Age\: ([0-9]+).+$

First grouping will return the age, see here or here.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

Can you try a full code with following concept:

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);
}

Robust way of doing is to get some Regular Expressions :) though...

bonCodigo
  • 14,268
  • 1
  • 48
  • 91
0

Supposing that you have age in this format 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 show you, your string value (if found)..

Sami
  • 8,168
  • 9
  • 66
  • 99
0

Actually you have data, which could be easily represented as dictionary of type 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());

Now you can get any value from your input string:

string occupation = dictionary["Occupation"];
int age = Int32.Parse(dictionary["Age"]);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • This is a good and possible solution but maybe the OP doen't have the data ready in variables (getting info from third-party e.g.). – voluminat0 Nov 09 '12 at 08:40
  • It does not make any difference where string comes from. As a final result we will have a variable referencing string data :) – Sergey Berezovskiy Nov 09 '12 at 08:49