1. 程式人生 > >C#---將字串按空格分隔

C#---將字串按空格分隔

string[] line = System.Text.RegularExpressions.Regex.Replace(strline.Trim(), @"[\s]+", " ").Split(" ".ToCharArray());

應用
將檔案mstreet解析為road.txt
mstreet

    9          mstreet                                5
663673.13   3545681.50 
663692.25   3545717.54 
663708.44   3545741.81 
663726.83   3545767.19 
663744.15   3545778.23 
   14          mstreet                                3
663072.13   3547152.70 
662910.24   3547161.54 
662809.83   3547167.01 
   15          mstreet                                2
663071.21   3547464.98 
662732.78   3547481.00 

road.txt

9   mstreet 663673.13   3545681.50
9   mstreet 663692.25   3545717.54
9   mstreet 663708.44   3545741.81
9   mstreet 663726.83   3545767.19
9   mstreet 663744.15   3545778.23
14  mstreet 663072.13   3547152.70
14  mstreet 662910.24   3547161.54
14  mstreet 662809.83   3547167.01
15  mstreet 663071.21   3547464.98
15  mstreet 662732.78   3547481.00
16  mstreet 663047.61   3547737.48
16  mstreet 662797.97   3547739.95
23  mstreet 669243.05   3548352.52
23  mstreet 669243.69   3548352.13
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter("road.txt", false);

            StreamReader sr = File.OpenText("mstreet");
            string strline;
            double x, y, roadID, num;
            while ((strline = sr.ReadLine()) != null)
            {
                string[] line = System.Text
.RegularExpressions.Regex.Replace(strline.Trim(), @"[\s]+", " ").Split(" ".ToCharArray()); for (int i = 0; i < 3; i++) Console.Write(line[i] + " "); Console.WriteLine(); roadID = Convert.ToDouble(line[0]); num = Convert.ToInt32(line[2]); for (int i = 0; i < num; i++) { strline = sr.ReadLine(); line = System.Text.RegularExpressions.Regex.Replace(strline.Trim(), @"[\s]+", " ").Split(" ".ToCharArray()); x = Convert.ToDouble(line[0]); y = Convert.ToDouble(line[1]); sw.WriteLine("{0}\t{1}\t{2:F}\t{3:F}", roadID, "mstreet", x, y); } } sw.Close(); sr.Close(); } }