Parsing Strings

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

If you simply wanted to see if the string contained the substring:

string myString = "Sent by Mel @4:20";
bool found = false;
if (myString.IndexOf("Mel") >= 0)
{
found = true;
}

Pete
 
If I understand you correct you want to extract the name "Mel" from the
string ( Mel is in this case )
if i'm correct you can use regular expressions.
the paterrn that i've test is
^Sent by (?'Name'\w+) @.+
so to get the string in the group "Name" you can use:

Regex r = new Regex("Sent by Mel @4:20");

Match m = r.Match ( "^Sent by (?'Name'\w+) @.+" );

Console.WriteLine(m.Groups["Name"].Value);

Regards

Martin
 
Hi Mel,

If strings are always in this format and you want to see who sent it this would do it.

string source = "Sent by Mel @4:20";
string sender = source.Split(null)[2];

The code splits the string into an array of words, where the sender is the 3rd word, index 2.

Happy coding!
Morten Wennevik [C# MVP]
 
Back
Top