字符串内的Java字符串

时间:2016-07-05 18:41:43

标签: java

编写一个程序,要求用户输入两个字符串,并打印第二个字符串出现在第一个字符串中的次数。例如,如果第一个String是“banana”而第二个是“an”,则程序将打印2。

以下是我目前的代码

public class Assignment4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Scanner answer = new Scanner(System.in);

//Prompt the user to enter a string
        System.out.println("Enter a word:");
        String input = answer.nextLine();

//Ask the user to enter a second String
        //look at index method of string
        System.out.println("Enter another word:");
        String input2nd = answer.nextLine();
        int counter = 0;
        for(int i=0; i<input.length(); i++) {
            if(input.charAt(i) == input2nd.charAt(0)) {
                counter++;

            } 
        }
        System.out.println(input2nd + " appears " + counter + " times.");

当我在第一个字符串中键入banana时,第二个字符串是“an”时,唯一出现的是数字3,它是出现3次的字符a,但不是2,因为它假设只有2“一个“

1 个答案:

答案 0 :(得分:0)

考虑一下我多年前学到的这个技巧:

  1. 用空字符替换原始单词中的搜索字词......
  2. 获取两者之间的差异...搜索的字符和原始的已替换
  3. 除以搜索词的len ...
  4. private static void searchString() {
    Scanner answer = new Scanner(System.in);
    // Prompt the user to enter a string
    System.out.println("Enter a word:");
    String input = answer.nextLine();
    
    // Ask the user to enter a second String
    // look at index method of string
    System.out.println("Enter another word:");
    String input2nd = answer.nextLine();
    String a = input.replace(input2nd, "");
    int counter = (input.length() - a.length()) / input2nd.length();
    System.out.println(input2nd + " appears " + counter + " times.");
    }
    

    输入香蕉一个将打印2