实现字符串分割

要求不使用String的split函数完成分割字符串功能

已给出方法:

  String[] splitString(String str,char sep)


郎朗坤
浏览 335回答 2
2回答

墨色风雨

1 public static string[] splitString(string str, char sep) 2 { 3 &nbsp;&nbsp; &nbsp;List<int> indexList = new List<int>(); 4 &nbsp;&nbsp; &nbsp;indexList.Add(0); 5 &nbsp;&nbsp; &nbsp;for (int i = 0; i < str.Length; i++) 6 &nbsp;&nbsp; &nbsp;{ 7 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (str[i] == sep) 8 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{ 9 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;indexList.Add(i);10 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}11 &nbsp;&nbsp; &nbsp;}12 &nbsp;&nbsp; &nbsp;indexList.Add(str.Length - 1);13 &nbsp;&nbsp; &nbsp;string[] ss = new string[indexList.Count - 1];14 &nbsp;&nbsp; &nbsp;for (int i = 0; i < ss.Length; i++)15 &nbsp;&nbsp; &nbsp;{16 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (indexList[i] == indexList[i + 1])17 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{18 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ss[i] = string.Empty;19 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}20 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;else21 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{22 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ss[i] = str.Substring(indexList[i] + 1, indexList[i + 1] - indexList[i] - 1);23 &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}24 &nbsp;&nbsp; &nbsp;}25 &nbsp;&nbsp; &nbsp;return ss;26 }主要原理就是先把对应字符的索引位置找出来,再根据索引位置提取字符串还有一种方法,可以直接在第一个循环中通过对比一个个字符,不相符就追加,相符就切割,但这样涉及大量连接字符串的操作

料青山看我应如是

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;}
打开App,查看更多内容
随时随地看视频慕课网APP