0

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

也许我想太多了,但唯一的办法是不要依赖各种字符串方法并创建自己的方法。我怎样才能让这种方法只将在读取的字符串/字符中找到的字符串/字符分配到数组中的一个位置,而不是全部以及阻止它添加不必要的输出?非常感谢帮助/建议

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

谢谢

4

1 回答 1

0

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

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

或者,如果您想使用 aList<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);
}
于 2013-09-09T01:45:14.810 回答