返回数组中以初始传递的字符串开头的字符串

时间:2018-09-02 04:50:46

标签: java arrays string

我有一个.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,因为存在以字母“ A”开头的4个状态。

现在我该如何创建一个传递字符并返回以该字符开头的所有状态的名称的新函数?例如,这是为此所需的初始返回类型,但是我在启动它时遇到了麻烦。该过程与我创建的 countStatesCountByInitial 函数相同吗?

public State[] CByInitial(char initial) {
        return new State[] {}; //to be completed    
    }   

2 个答案:

答案 0 :(得分:1)

是的,它将与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所言,我们可以避免使用List来初始化状态的大小,而使用countStatesCountByInitial

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;
} 

答案 1 :(得分:0)

您只需使用一种方法即可完成这两项操作。

public static ArrayList<State> getStatesCountByInitial(char initial) {
        ArrayList selectedStates = new ArrayList<State>();
        for(int i = 0; i < states.length; i++) {
            if(states.charAt(0) == initial){
                selectedStates.add(states[i]);
            }
        }
        return selectedStates;
}

此方法将返回一个数组列表。 如果要获取计数,请调用此方法并获取数组的大小。

ArrayList<State> statesNew = getStatesCountByInitial('A');
int count = statesNew.size();