2016-07-05 4 views
-3

사용자에게 두 개의 String을 입력하도록 요청하는 프로그램을 작성하고 두 번째 String이 첫 번째 String 내에 나타나는 횟수를 인쇄합니다. 첫 번째 문자열은 "바나나"이며, 예를 들어, 두 번째 "는"다음문자열 내부의 Java 문자열

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

내가 먼저 문자열로 바나나를 입력

하고, 두 번째 문자열은 "an"이고 유일한 것은 3 번이며 3 번 나타나는 문자 A는 2 "가 아니면 안된다."

+0

[indexOf] (https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf (java.lang.String, % 20int))를 사용하십시오. –

답변

0

이 트릭을 내가 몇 년 동안 생각해 보았다. 전 :

  1. 는 ... 양자의 길이의 DIFF를 얻을 문자를 검색하여 원래의 검색 단어의 LEN 의해
  2. 분할 그 대체 ... emptychars하여 일본어 단어로 단어를 검색
입력 바나나 와 함께

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

관련 문제