Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello everybody,

I'm quite new to programming, and I'm following a video-course in order to learn C#.

I need a little help to do this exercise:

  1. Open a .TXT file with strings like this:
    +01/01/1918 11:59:59-1-2-3+

  2. Retrieve the strings (one by one I presume) and get the numbers preceded by the "-" delimiter
    (in this case, the numbers: 1 2 3)
  3. Evaluate every number (must be 0<n><10)>
  4. If a number is out of range, show a message (console) and process the next string


Thank you for your help.
Posted
Updated 19-Jun-11 15:45pm
v2

1) Trim leading/trailing '+': myLine = myLine.Trim(new char[] {'+'});

2) Split each line by '-': use: char[] terms = myLine.Split(new char[] {'-'});

3) The split will give you array of char with 4 terms; parse first one (terms[0]) to System.DateTime using System.DateTime.Parse(string, IFormatProvider, DateTimeStyles) or System.DateTime.ParseExact(string, string, IFormatProvider); make sure to use appropriate CultureInfo as an instance of IFormatProvider to match culture-specific date/time format (from your example, one cannot understand which number is month and which is day, but you should know this from the culture); in second case, use appropriate explicit format string (see references below).

4) Parse other terms using your type; as '-' is a delimiter and not sign, your type is unsigned; so it could be byte, ushort, uint, ulong; in all cases, use Parse or TryParse, for example uint.Parse(term[index]), where your index is 1 to 3.

See:
http://msdn.microsoft.com/en-us/library/system.string.aspx[^],
http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^],
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx[^],
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^].

—SA
 
Share this answer
 
v2
static void Main(string[] args)
{
    string text = "+01/01/1918 11:59:59-1-2-3+";
    string[] words = text.Split('-');
    List<string >buffer=new List<string>();
    //Initial vords
    foreach (var word in words)
    {
        Console.WriteLine(word);
        buffer.Add(word);
    }
    buffer.Remove(buffer[0]);//remove first words
    buffer[2] = buffer[2].Remove(buffer[2].Length - 1, 1);//remove simbol +
    //Show final list with result : 1, 2 , 3
    foreach (var aux in buffer)
    {
        Console.WriteLine(aux);
    }
    Console.ReadLine();
}
 
Share this answer
 
Depending on whether the rest of the format is always safe (it doesn't contain -digit), you can extract all the numbers with a regex "-\d*". If they are always right next to each other you can use "(-\d*)+", which will match once, and its inner groups will be each number.
 
Share this answer
 

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