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

标签 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,因为有 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/

相关文章:

Java 类未从 IIB 中的 javaclassloader 服务加载

java - 如果我有下一个结构,如何从 Firebase 实时数据库检索所有数据?

php使用ceil函数在多列中显示数组数据

c - 需要创建一个返回 int 的函数,该函数基于哪个 char 参数具有更多大写字母

php - 在 camelCased 字符串中的单词之间添加空格,然后大写第一个单词

string - 为什么 `str` 封装在 `String` 中而不是 `Box<str>` 中?

java - 自定义 xml 格式 eclipse

java - 如何在 log4j 的配置文件中为文件附加程序提供环境变量路径

PHP重新索引数组?

javascript - 如何将 sdtout 从服务器返回到字符串内的客户端?