猿问
回到首页
个人中心
反馈问题
注册登录
下载APP
首页
课程
实战
体系课
手记
专栏
慕课教程
实现字符串分割
要求不使用String的split函数完成分割字符串功能
已给出方法:
String[] splitString(String str,char sep)
郎朗坤
浏览 335
回答 2
2回答
墨色风雨
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 else21 {22 ss[i] = str.Substring(indexList[i] + 1, indexList[i + 1] - indexList[i] - 1);23 }24 }25 return ss;26 }主要原理就是先把对应字符的索引位置找出来,再根据索引位置提取字符串还有一种方法,可以直接在第一个循环中通过对比一个个字符,不相符就追加,相符就切割,但这样涉及大量连接字符串的操作
0
0
0
料青山看我应如是
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;}
0
0
0
打开App,查看更多内容
随时随地看视频
慕课网APP
继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续