Given a variable length string (11:15 OR 9:30), how do I use Substring to pull out the first number?

This works if the hour is 11:15
myTime.Substring(0,2)

This works if the hour is 9:30
myTime.Substring(0,1)

How do I make it so it works with either string? I don't know ahead of time how long the string is.
LVL 2
M3hcSSAsked:
Who is Participating?
 
neilpriceCommented:
Assuming you have the colon everytime you can use;

myString.Substring(0, myString.IndexOf(':'));

For example see below;

using System;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "9:30";
            string s2 = "11:55";

            string s3 = s1.Substring(0, s1.IndexOf(':'));
            string s4 = s2.Substring(0, s2.IndexOf(':'));

            Console.WriteLine(s3);
            Console.WriteLine(s4);
            Console.ReadLine();
        }
    }
}
0
 
M3hcSSAuthor Commented:
That's actually a really freaky answer.
0
 
M3hcSSAuthor Commented:
To get the minutes to the right side of the colon...

JUNKTimeOn1.Substring((JUNKTimeOn1.IndexOf(":")+1),2)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.