一個分割string的程式

來源:互聯網
上載者:User

論壇求助要實現的一個功能。

實現代碼如下:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Date1223_2
...{
    class SpiltString
    ...{
        //假設一行資料中,有很多組資料,每組資料用“||”分開
        //如果只有兩組資料,不用遞迴那麼麻煩。
        //對一行資料進行第一次分離
        public ArrayList FirstSpilt(string str)
        ...{
            int i = str.IndexOf("|");
            int ct = str.Length;
            string str1 = null;
            
            ArrayList list = new ArrayList();
            if (i > 0)
            ...{
                str1 = str.Substring(0, i);
                string str2 = str.Substring((i + 2), (ct - i - 2));
                list = FirstSpilt(str2);
               
            }
            else
            ...{
                str1 = str;
            }
            list.Add(str1);
            return list;
        }

        //第二次分離。使用到了“out”
        public void SecondSpilt(string str, out string name, out string gender, out int age)
        ...{
            int indexA = str.IndexOf("a");
            int indexB = str.IndexOf("b");
            name = str.Substring(0, indexA);
            gender = str.Substring(indexA+1, indexB - indexA-1);
            age = Int32.Parse(str.Substring(indexB+1,str.Length-indexB-1));
        }

        
    }

    class Test
    ...{
        public static void Main(String[] args)
        ...{
            string str = "張三a男b20||李四a男b25||錢五a女b18";

            SpiltString ss = new SpiltString();
            ArrayList list = ss.FirstSpilt(str);
            string name;
            string gender;
            int age;

            foreach (object obj in list)
            ...{
                //資料徹底分離
                ss.SecondSpilt(obj.ToString(), out name, out gender, out age);

                //列印。這裡可以將name,gender,age,插入資料庫
                Console.WriteLine(name + " " + gender + " " + age);
            }

            Console.ReadLine();
            
        }
    }
}

 這個程式,還是很粗糙,基本上都是按照特定的需求來分割的,如果想實現輸入任意分割符,就能分割,那就比較好了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.