Java,写自己的字符串拆分方法

标签 java string split

我需要能够编写自己的拆分字符串方法,以便像这样输入

String[] test1 = mySplit("ab#cd#efg#", "#");
System.out.println(Arrays.toString(test1));

将打印 [ab, #, cd, #, efg, #] 到控制台。 到目前为止,我已经把它像那样拆分了,但我的方式留下了尴尬的空间,其中 2 个分隔符在一行中,或者分隔符在输入的开头。

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;
}

当我在测试主程序中使用该方法时,我得到输出 [ab, #, cd, #, efg, #, , , , ]。所以我不知道如何修复它们的间距,我还需要能够允许我的代码当前无法处理的多个定界符。

我也知道这段代码现在真的很草率,只是想在优化之前放下概念。

最佳答案

问题很简单,您有一个偏移量遍历查找新匹配项 (pos),另一个偏移量显示您找到匹配项的最后一个位置的结尾 (start)。

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;
}

这避免了额外的循环并且每个字符只复制一次。实际上,由于子字符串的工作方式,不会复制任何字符,只会创建指向原始字符缓冲区的小字符串对象。根本没有进行字符串连接,这是一个重要的考虑因素。

关于Java,写自己的字符串拆分方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340120/

相关文章:

java - 反射 - Method::get Generic Return Type no generic - 可见性

python - Pandas DataFrame - 提取两个字符串之间的字符串并包含第一个分隔符

java - Neo4j-Spring Data-如何避免嵌套属性成为 Neo4j 中的节点

java - 如何在矩形图形中居中放置标签

java - 提取 : and WORD in java using regex in java 之间的子字符串

Python和excel读取文件问题

python/numpy 一次合并 4 行子数组

split - ItextSHARP 表拆分问题

optimization - ClientBundle 图像资源的 GWT 代码拆分模式

java - 我们可以使用扫描仪输入将值插入 jdbc 程序中的数据库吗