首页 > 解决方案 > 如何使用方法 indexOf 搜索字符串

问题描述

14.11(搜索字符串) 编写一个应用程序,输入一行文本和一个搜索字符,并使用 String 方法 indexOf 确定该字符在文本中出现的次数。14.12(搜索字符串) 根据练习 14.11 中的应用程序编写一个应用程序,输入一行文本,并使用 String 方法 indexOf 确定文本中每个字母的出现总数。大写字母和小写字母应该一起计算。将每个字母的总数存储在一个数组中,并在总数确定后以表格格式打印值。我现在的问题是如何确定单词中每个字母的出现。比如单词“occurrence”,每个字母在这个单词中出现了多少次。

我已经根据我的理解编写了我的代码,我的代码可以显示字符并以表格形式返回它们的索引。但这并不是问题所需要的。

import java.util.*;

public class Searching
{
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter Text: ");
    String text1 = input.nextLine();
    char[] text2 = text1.toCharArray();
    System.out.println("Character   Index");
    for(int i = 0; i < text2.length; i++)
    {
System.out.printf("%s%12d%n", text2[i],text1.indexOf(text2[i], i));
    }
}
} 

我希望实际输出采用表格格式。“出现”这个词,我的代码应该显示每个字母以及它出现的次数。字母频率 o 1 c 3 u 1 r 2 e 2 n 1

标签: java

解决方案


如果您使用HashMap可以吗?这是 14.12 的解决方案:

Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
//So we only have to find lower case chars
String input = in.nextLine().toLowerCase();

//Add every single character in the word
//We use a LinkedHashMap instead of a HashMap to retain character order during printing.
LinkedHashMap<Character, Integer> characterCount = new LinkedHashMap<>();
for(int i = 0; i < input.length(); i++) {
    characterCount.put(input.charAt(i), 0);
}

//Iterate from every character ranging from a - z
//It would be more ideal to iterate only over the characters
//in the word. But your requirement asked to iterate over the alphabet.
for(int i = 'a'; i <= 'z'; i++) {
    //This is the character we are currently searching for
    Character searchingFor = (char)i;
    int startingIndex = 0; int foundIndex = 0;
    //Search for the character in the string FROM a specfic index (startingIndex in this case)
    //We update startingIndex to a bigger index in the string everytime we find the character.
    while((foundIndex = input.indexOf(searchingFor, startingIndex)) != -1) {
        //it must be the index+1 so the next time it checks after the found character.
        //without the +1, it's an infinite loop.
        startingIndex = foundIndex + 1;
        //Update count to the current value + 1
        characterCount.put(searchingFor, characterCount.get(searchingFor) + 1);
    }


}

//Print the results
for(Character c : characterCount.keySet()) {
    System.out.printf("%s%12d%n", c, characterCount.get(c));
}

in.close();

单词“occurrence”的控制台输出:

Enter text: occurence
o           1
c           3
u           1
r           1
e           2
n           1

推荐阅读