Click here to Skip to main content
13,057,089 members (43,921 online)
Rate this:
Please Sign up or sign in to vote.
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 19-Jun-11 12:06pm
Updated 19-Jun-11 15:45pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.


Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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)
    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)
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170728.6 | Last Updated 20 Jun 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100