我有一个 .txt 文件,其中包含以下各州的数据:
AL,Alab,4860
AK,Alas,7415
AZ,Ariz,6908
AR,Arka,2988
我创建了一个函数,用于计算有多少个从初始传递开始的状态:
public int CInitial(char initial) {
int total = 0;
for(int i = 0; i < states.length; i++) { //states is an array which includes all states present in the .txt file
String testString = states[i].getName(); // getName gets the name of the states present in the .txt file
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
total++;
}
}
}
return total;
}
如果传递“A”,则返回数字 4;如果传递任何其他首字母缩写,则返回 0,因为有 4 个州以字母“A”开头。
现在如何创建一个新函数来传递一个字符并返回以该字符开头的所有状态的名称?例如,这是所需的初始返回类型,但是我在启动它时遇到了麻烦。该过程与我创建的 countStatesCountByInitial 函数相同吗?
public State[] CByInitial(char initial) {
return new State[] {}; //to be completed
}
最佳答案
是的,它与countStatesCountByInitial
非常相似。主要区别是每次找到匹配项时,您都希望将状态添加到数组中。由于我们事先不知道数组的大小,因此我们可能需要使用 List
来代替。
public State[] getStatesCountByInitial(char initial) {
ArrayList<State> found = new ArrayList<>();
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the list
found.add(states[i]);
}
}
}
// return as array
return found.toArray(new State[found.size()]);
}
根据 Patrick 的建议,我们可以通过使用 countStatesCountByInitial
来初始化状态的大小,从而避免使用 List
。
public State[] getStatesCountByInitial(char initial) {
int matchSize = countStatesCountByInitial(initial);
States[] found = new States[matchSize];
int foundIndex = 0;
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the array
found[foundIndex] = states[i];
foundIndex++;
}
}
}
// return the array
return found;
}
关于java - 返回数组中以初始传递的字符串开头的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52134058/