splitting lines in a file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aphoorva a
    New Member
    • Oct 2011
    • 2

    #1

    splitting lines in a file

    hi,
    am trying to split lines in a file in such a way
    where ever and or dot(.) comes in a file the line should get splitted

    my code is working only for .(dot)not for (and)

    code is as shown below
    Code:
    static void Main(string[] args)
    {
      int i = 1;
      foreach (string line1 in File.ReadAllLines(@"g:/employee.txt"))
      {
        string[] srs = line1.Split('and','.');
        foreach (string dot in srs)
        {
            Console.WriteLine("{0}:{1}",i,dot);
            i++;
        }
      }
      Console.ReadLine();
    }

    with regards
    aphoorva
    Last edited by Frinavale; Oct 25 '11, 05:34 PM. Reason: Added code tags, formatted code so that it is more legible and added the ending '}' for the main method.
  • arie
    New Member
    • Sep 2011
    • 64

    #2
    In c# there is no String.Split() method that has two "separators ", one of the type of char, and second of the type of string, as its parameters (list of Split() methods: http://msdn.microsoft.com/en-us/library/y7h14879.aspx )

    To split by char (e.g. '.') you do:
    Code:
    string[] srs = line1.Split('.');
    To split by string you can also do:
    Code:
    string[] srs = Regex.Split(line1, "and");
    I don't know if there is a method in framework to split string using two different separators, I guess you can write your own. Or there can be some regex pattern that you can use with Regex.Split() method, but I know about regex patterns only that they are out there :(

    Some split examples: http://www.dotnetperls.com/string-split

    Comment

    • arie
      New Member
      • Sep 2011
      • 64

      #3
      I found the regex pattern that does the trick:

      Code:
      string pattern = @"((and)|(\.))";
      string[] srs = Regex.Split(line1, pattern);
      The only problem is that it includes every "and" and "." in the table srs so you'll have to remove them later.

      Comment

      Working...