我正在研究课堂上的一个学习问题,基本上它读取一个字符串和一个字符。字符是分隔符。然后它将在字符串中搜索分隔符并创建一个长度与找到分隔符的次数相等的数组。然后它将每个字符或字符串分配到数组中它自己的位置并返回它。
也许我想太多了,但唯一的办法是不要依赖各种字符串方法并创建自己的方法。我怎样才能让这种方法只将在读取的字符串/字符中找到的字符串/字符分配到数组中的一个位置,而不是全部以及阻止它添加不必要的输出?非常感谢帮助/建议
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
谢谢