Java,编写自己的split string方法
发布时间:2020-05-24 12:45:38 所属栏目:Java 来源:互联网
导读:我需要能够编写自己的分割字符串方法,以便输入像 String[] test1 = mySplit(ab#cd#efg#, #);System.out.println(Arrays.toString(test1)); 将[ab,#,cd,#,efg,#]打印到控制台. 到目前为止,我已经让它像那样拆分但是我的方式留下了尴尬的空间,其中2个分隔符连续
|
我需要能够编写自己的分割字符串方法,以便输入像 String[] test1 = mySplit("ab#cd#efg#","#");
System.out.println(Arrays.toString(test1));
将[ab,#,cd,efg,#]打印到控制台. public static String[] mySplit(String str,String regex)
{
String[] storeSplit = new String[str.length()];
char compare1,compare2;
int counter = 0;
//Initializes all the string[] values to "" so when the string
//and char concatonates,'null' doesn't appear.
for(int i=0; i<str.length(); i++) {
storeSplit[i] = "";
}
//Puts the str values into the split array and concatonates until
//a delimiter is found,then it moves to the next array index.
for(int i=0; i<str.length(); i++) {
compare1 = str.charAt(i);
compare2 = regex.charAt(0);
if(!(compare1 == compare2)) {
storeSplit[counter] += ""+str.charAt(i);
} else {
counter++;
storeSplit[counter] = ""+str.charAt(i);
counter++;
}
}
return storeSplit;
}
当我在Test main中使用该方法时,我得到输出[ab,].所以我迷失了如何修复它的间距,我还需要能够允许我的代码当前无法处理的多个分隔符. 另外我知道这个代码目前非常草率,只是试图在优化之前放下概念. 解决方法问题很简单,你有一个偏移通过寻找新的匹配(pos),另一个显示然后结束你找到匹配(开始)的最后一个地方.public static String[] mySplit(String str,String regex)
{
Vector<String> result = new Vector<String>;
int start = 0;
int pos = str.indexOf(regex);
while (pos>=start) {
if (pos>start) {
result.add(str.substring(start,pos));
}
start = pos + regex.length();
result.add(regex);
pos = str.indexOf(regex,start);
}
if (start<str.length()) {
result.add(str.substring(start));
}
String[] array = result.toArray(new String[0]);
return array;
}
这样可以避免额外的循环并仅复制每个字符一次.实际上,由于子字符串的工作方式,不会复制任何字符,只会创建指向原始字符缓冲区的小字符串对象.根本没有串联串联,这是一个重要的考虑因素. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
