2016-07-05 274 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