論壇求助要實現的一個功能。
實現代碼如下:
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();
}
}
}
這個程式,還是很粗糙,基本上都是按照特定的需求來分割的,如果想實現輸入任意分割符,就能分割,那就比較好了。