Click here to Skip to main content
15,912,578 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
string a="31/2/2014"
i want to print 2 in string ,how to get it
Posted
Comments
Matt T Heffron 30-Jan-14 16:16pm    
This is VERY unclear!
do you:
1) want to extract the middle number (month?) from the string
2) want the first digit of the third number (year?)
Use "Improve question" to clarify.
Member 10523388 30-Jan-14 16:19pm    
i want to extract middle number[month]
Kornfeld Eliyahu Peter 30-Jan-14 16:24pm    
So it's ain't a string but a date! Use it as a date and you will got the tool to extract the month...
King Fisher 30-Jan-14 23:35pm    
string a="31/2/2014";


is this the static one?

If it really is a string then:
C#
string a="31/2/2014";
string[] parts = a.Split('/');
if (parts.Length >= 2)
{
  return parts[1];    // and parts[0] has the day and parts[2] has the year
}
else
  // bad input


If it really is a DateTime then:
C#
DateTime dt = new DateTime(2014, 2, 31);
int month = dt.Month;
 
Share this answer
 
There are quite a few ways you could do that:
1) string.Substring - easy... Just give it the offset and length and it'll do it.
2) regex - a bit more complex, you set up as pattern that extracts the month without needing to know the offsets, because it can cope with variable length day and month numbers.
3) convert it to a DateTime and extract the month from that.

The last is pretty easy: just use DateTime.Parse of the string, and then access the DateTime properties to get your month.

Me? I'd go with the DateTime every time!
 
Share this answer
 
Comments
Karthik_Mahalingam 30-Jan-14 18:56pm    
5, well said.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900