2 回答

TA貢獻1853條經驗 獲得超6個贊
1 public static string[] splitString(string str, char sep)
2 {
3 List<int> indexList = new List<int>();
4 indexList.Add(0);
5 for (int i = 0; i < str.Length; i++)
6 {
7 if (str[i] == sep)
8 {
9 indexList.Add(i);
10 }
11 }
12 indexList.Add(str.Length - 1);
13 string[] ss = new string[indexList.Count - 1];
14 for (int i = 0; i < ss.Length; i++)
15 {
16 if (indexList[i] == indexList[i + 1])
17 {
18 ss[i] = string.Empty;
19 }
20 else
21 {
22 ss[i] = str.Substring(indexList[i] + 1, indexList[i + 1] - indexList[i] - 1);
23 }
24 }
25 return ss;
26 }
主要原理就是先把對應字符的索引位置找出來,再根據索引位置提取字符串
還有一種方法,可以直接在第一個循環中通過對比一個個字符,不相符就追加,相符就切割,但這樣涉及大量連接字符串的操作

TA貢獻1772條經驗 獲得超8個贊
String[] splitString(String str,char sep){
ArrayList<String> l =new ArrayList<String>();
int n;
while((n=str.indexOf(sep))>=0){
String pStr=null;
pStr=str.substring(0,n);
if(pStr!=null && !pStr.equals(""))
l.add(pStr);
str=str.substring(n+1,str.length());
}
if(str!=null && !str.equals(""))
l.add(str);
String s[] = new String[l.size()];
l.toArray(s);
return s;
}
- 2 回答
- 0 關注
- 304 瀏覽
添加回答
舉報