Java:创建一个具有输入/输出的分隔符方法



我正在研究课堂上的一个学习问题,本质上它读取了一个字符串和一个字符。 字符是分隔符。 然后,它将在字符串中搜索分隔符,并创建一个长度与找到分隔符的次数相等的数组。 然后,它将每个字符或字符串分配给数组中自己的位置并返回它。

也许我想多了,但只是不依赖各种字符串方法,而是创建自己的字符串方法。 如何让此方法仅将读取的字符串/字符分配给数组中的一个位置,而不是全部,并阻止它添加不必要的输出? 非常感谢帮助/建议

public static String[] explode(String s, char d){
    String []c;
    int count = 1;
    //checks to see how many times the delimter appears in the string and creates an      array of corresponding size
    for(int i = 0; i < s.length(); i++){
        if(d == s.charAt(i))
            count ++;
    }
    c = new String [count];
    //used for checking to make sure the correct number of elements are found
    System.out.println(c.length);
    //goes through the the input string "s" and checks to see if the delimiter is found
    //when it is found it makes c[j] equal to what is found
    //once it has cycled through the length of "s" and filled each element for c, it returns the array
    for(int i = 0; i < s.length(); i++){
            for(int j = 0; j < c.length; j++){
                if(d == s.charAt(i))
                    c[j] += s.substring(i-1);
            }
    }
    //provides output for the array [c] just to verify what was found
    for(int y = 0; y < c.length; y++)
        System.out.println(c[y]);
    return c;
}
public static void main(String [] args){
    String test = "a,b,c,d";
    char key = ',';
    explode(test,key);
}

    ^The following will output:
    4
    nulla,b,c,db,c,dc,d
    nulla,b,c,db,c,dc,d
    nulla,b,c,db,c,dc,d
    nulla,b,c,db,c,dc,d
    I'm aiming for:
    4
    a
    b
    c
    d

谢谢

也许你可以尝试这样的事情:

public static void main(String[] args){
    explode("a,b,c,d", ',');
}
public static void explode(final String string, final char delimiter){
    int length = 1;
    for(final char c : string.toCharArray())
        if(delimiter == c)
            length++;
    if(length == 1)
        return;
    final String[] array = new String[length];
    int index, prev = 0, i = 0;
    while((index = string.indexOf(delimiter, prev)) > -1){
        array[i++] = string.substring(prev, index);
        prev = index+1;
    }
    array[i] = string.substring(prev);
    System.out.println(length);
    for(final String s : array)
        System.out.println(s);
}

上述程序的输出为:

4

a

b

c

d

或者,如果你想使用List<String>(和Java 8),你可以通过做这样的事情来删除几行:

public static void explode(final String string, final char delimiter){
    final List<String> list = new LinkedList<>();
    int index, prev = 0;
    while((index = string.indexOf(delimiter, prev)) > -1){
        list.add(string.substring(prev, index));
        prev = index+1;
    }
    list.add(string.substring(prev));
    System.out.println(list.size());
    list.forEach(System.out::println);
}

最新更新