【问题标题】:Splitting a string into an array, and search for a string将字符串拆分为数组,然后搜索字符串
【发布时间】:2016-06-16 16:08:04
【问题描述】:

所以我将一个字符串拆分为一个数组,我想询问用户要搜索的单词,在数组中搜索所选单词并输出单词的每个位置。但是,indexOf 函数似乎无法搜索数组?我可以做任何更正吗?

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    String str = "Java String to String Array Example";

    String strArray[] = str.split(" ");
    String word;
    int baby;

    System.out.println("Please enter a message");
    word = scan.nextLine();

    baby = strArray.indexOf(word);

    while (baby >= 0) {
        System.out.println("The word occurs at index " + baby);

        baby = strArray.indexOf(word, baby + word.length());

        for (int counter = 0; counter < strArray.length; counter++) {
            System.out.println(strArray[counter]);
        }
    }
}

【问题讨论】:

标签: java arrays split indexof


【解决方案1】:

您可以使用正则表达式获取每个匹配单词的起始索引。
请看这个例子:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    String str = "Java String to String Array Example";

    String strArray[] = str.split(" ");
    String word;
    int baby;

    System.out.println("Please enter a message");
    word = scan.nextLine();

    ArrayList<Integer> positions = new ArrayList();
    Pattern p = Pattern.compile(word);
    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.println("Occurs at position: " + m.start());
        positions.add(m.start());
    }
}

【讨论】:

    【解决方案2】:

    首先,indexOf 方法不存在用于简单数组 - 它是 List 接口的方法,由 ArrayList 实现。

    您在int baby 中存储的索引实际上不是字符串中单词的索引,而是单词计数 - 即 0 是第一个单词,1 是第二个单词。

    indexOf 方法在第一次出现时停止,因此不太适合我认为您正在尝试做的事情。

    这会做我认为你想要的:

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = "Java String to String Array Example";
        List<String> strArray = Arrays.asList(str.split(" "));
    
        System.out.println("Please enter a message");
        String word = scan.nextLine();
    
        for (int i = 0; i < strArray.size(); i++)
            if (strArray.get(i).equals(word))
                System.out.println(word + " found at location " + i);
    
    }
    

    【讨论】:

    • 在不使用列表功能的情况下,为什么要转换为列表?您可以保留数组并循环遍历数组。
    • True - 当我使用 OP 使用 indexOf() 方法时,只剩下代码。你是完全正确的,不需要列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多