I am trying to get the characters that appear before and after certain character ("-").

string val = "7896-2-5";
    7896-2-5 here I want to get the character that appear between the two dashes i.e. 2
string val = "4512-12-5"; 
    4512-12-5 so here 12,

the position of first appearance of - is fixed from left side but the position of second appearance of - is determined by the character in between the two - , may be single digit or double digit number.

How can I get the characters?

2 Answers

2
Janus Pienaar On

Easiest would be to use string.Split('-')

e.g.

var middleDigit = string.Split('-')[1];
0
Seyed Reza Dadrezaei On

if your string should have tow dashes try this:

string myString = "4512-12-5";
string result="";
if(myString.Count(f => f =='-') == 2)
    result = myString.Substring(myString.IndexOf('-') + 1 ,myString.LastIndexOf('-') - myString.IndexOf('-') - 1);
else
    result = "string is not well formated";
Console.WriteLine(result);