2016-07-05 115 views
-3

編寫一個程序,要求用戶輸入兩個字符串,並打印出第二個字符串出現在第一個字符串內的次數。例如,如果第一個字符串是「香蕉」,第二是「一」,該程序將打印2字符串內部的Java字符串

下面是我到目前爲止的代碼

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."); 

當我鍵入香蕉切成第一串,和第二個字符串是「an」,唯一出現的是數字3,它是出現3次的字符a,但不是2,因爲它假設只是2「an」

+0

使用[indexOf](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)) –

回答

0

考慮這個技巧,前:

  1. 替換由emptychars原詞搜索詞...
  2. 得到兩者的長度之間的差異...搜索字符和原來與搜索詞的LEN換成
  3. 除以...

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