我想要编写代码,将一个字符串分割成单独的子字符串,每个子字符串都有3个字符,并将它们分配给一个字符串数组--例如,字符串"abcdefg“可以被吐到"abc”、"bcd“、"cde”、"efg“,这些字符串被分配给一个字符串数组。我有下面的代码,它得到了一个错误:
String[] words = new String[] {};
String sequence = "abcdefg";
int i;
for(i = 0; i <= sequence.length()-3; i++) {
words[i] = sequence.substring(i, 3+i);
System.out.println(words[i]);
}发布于 2014-11-03 08:25:05
改为使用以下代码:
String sequence="abcdefg";
String[] words=new String[sequence.length()-2];
int i;
for(i=0;i<=(sequence.length()-3);i++){
words[i]=sequence.substring(i,3+i);
System.out.println(words[i]);
}或者您可以使用字符串数组。
发布于 2014-11-03 08:17:56
String[] words=new String[] {}; // empty array你有空数组。
words[i] // when i=0空array与0th匹配时不存在索引。
解决方案。
您可以在定义array时定义数组的大小。最好的方法是从length获得sequence
String sequence="abcdefg";
String[] words=new String[sequence.length()];发布于 2014-11-03 08:29:56
您可以从序列字符串中获取长度,除以要存储的字符数,以便知道数组应该有多大。例如
String sequence="abcdefg";
int myLength = sequence.length/3;
String[] words=new String[myLength];然后,您可以使用该长度填充数组。
for(i=0;i<=myLength;i++){
words[i]=sequence.substring(i,3+i);
System.out.println(words[i]);
}https://stackoverflow.com/questions/26710208
复制相似问题