如何使用方法indexOf搜索字符串

时间:2019-02-01 21:16:10

标签: java

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

据我所知,我已经编写了代码,并且代码可以显示字符并以表格形式返回其索引。但这不完全是问题所需要的。

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 你1 22 2号 n 1

1 个答案:

答案 0 :(得分:0)

如果你使用一个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