2017-12-04 18 views
-6

몇 가지 설명이있는 예를보고 싶습니다. 개체를 비교하기 위해 어떤 문자열 함수를 사용합니까? 추가 문자없이 각 문자 또는 실제 단어를 비교합니까?자바에서 텍스트 파일 내에서 문자열을 찾는 방법

감사합니다.

+1

당신이 누군가 당신의 숙제를하고 싶어하는 것처럼 들린다 – Kon

+0

나는 1 조 달러를 원하지만 약간의 노력 없이는 그렇게되지 않을 것입니다. 시도하고 관리 할 청크로 질문을 세분화. 'String' 내에서 문자열을 찾을 수있는 방법은 여러 가지가 있습니다. 수동으로 ('String # contains')하거나'RegularExpression'을 사용하여 텍스트의 패턴을 찾을 수 있습니다. 다시 찾으려고. 파일을 읽는 것은 일반적으로 그다지 어렵지 않으며 가능한 방법을 보여주는 몇 가지 가능한 예가 있습니다. – MadProgrammer

+0

@Kon 현재 어떤 JAVA 과정에 있지 않습니다. 오직 C. 나는 혼자서 자바를 배우기를 원했지만 객체에 익숙하지 않다. –

답변

0

나는 잠시 전에이 질문과 매우 비슷한 것을 시도했다. Java에서이 작업을 수행하는 데는 여러 가지 방법이 있지만 Scanner 클래스와 File 클래스를 사용했습니다.

public static void main(String[] args) 
{ 
    Scanner input = new Scanner(System.in);  //Just a normal scanner 

    System.out.println("Please enter in the pathname to the file you want to view."); 
    String pathname = input.nextLine();   //Pathname to text file 
    File book = new File(pathname);    //Creating a new file using the pathname 

    if(book.canRead() == false)     //If Java cant read the file, this will pop up 
    { 
     System.out.println("Your file cannot be read"); 
    } 
    else if(book.canRead() == true)    //If Java can read the file, then this asks for the word to search for 
    { 
     System.out.println("Please enter in the word you wish to search for."); 
     wordToSearchFor = input.nextLine(); 

     wordCounter(book);      //Calls the method 
    } 

    System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname); 

} 

이 당신이 그것을 EX주는 패스의 기반으로 파일을 만들려면 파일 클래스를 사용하는 주요 방법입니다 - C를 : \ 사용자 알렉스 \ 다운로드 \ 내가 다음에 확인 mobydick.txt \ 당신이 할 수있는 경우 다음 내가에서 수행 주먹 것 인, 분석하는 File 객체를 취할 수 있습니다 자바

import java.io.*; 
import java.util.Scanner; 

public class TextReader 
{ 
    private static int numOfOccurrences;   //Counter to keep track of the number of occurances 
    private static String wordToSearchFor;  //String field so both methods can access it 

    /* 
    * This method takes in the file of the book so the scanner can look at it 
    * and then does all of the calculating to see if the desired word appears, 
    * and how many times it does appear if it does appear 
    */ 

    public static void wordCounter(File bookInput) 
    { 
     try           
     {            
      Scanner bookAnalyzer = new Scanner(bookInput);  //Scanner for the book 

      while(bookAnalyzer.hasNext())      //While the scanner has something to look at next 
      { 
       String wordInLine = bookAnalyzer.next();  //Create a string for the next word 

       wordInLine = wordInLine.toLowerCase();   //Make it lowercase 
       String wordToSearchForLowerCase = wordToSearchFor.toLowerCase(); 
       String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + "."; 

       if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length()) 
       { 
        numOfOccurrences++; 
       } 
       else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length()) 
       { 
        numOfOccurrences++; 
       } 
      } 
     } 

     catch(FileNotFoundException e)    //Self explanitory 
     { 
      System.out.println("The error is FileNotFoundException - " + e); 
      System.out.println("This should be impossible to get to because error checking is done before this step."); 
     } 
    } 

스캐너 책 자체를 분석하는 메서드를 호출하면 파일을 읽을 수 있는지 확인하고, 이 방법. 그런 다음 while 루프를 사용하여 현재 단어 다음에 단어가 있는지 스캐너에 묻습니다. 단어가있는 한 계속 실행됩니다. 그런 다음 비교할 참조로 사용할 현재 단어의 String을 만듭니다. 그런 다음 String 클래스와 함께 제공되는 메서드를 사용하여 대문자와 소문자가 중요하기 때문에 모든 것을 소문자로 만듭니다.

이 메서드의 첫 번째 if 문은 스캐너 클래스의 현재 단어가 String 클래스의 indexOf 메서드를 사용하여 검색 한 단어와 일치하는지 확인합니다.이 문자열은 일부 문자열을 가져 와서 다른 문자열에 있는지 확인합니다. if 문 비교는 또한 원하는 단어 길이가 책에서 단어 길이와 동일하다는 것을 확인합니다. "the"를 찾으면 "the"가 포함되어 있기 때문에 "then"을 단어로 표시하지 않습니다. 두 번째 if 문은 끝 부분에 마침표가있는 원하는 단어로 동일한 작업을 수행합니다. 여분의 마일을 가고 싶다면 느낌표, 물음표, 쉼표 등을 확인할 수도 있지만 시간을 확인하기로 결정했습니다.

이러한 if 문 중 하나가 올 바르면 변수를 하나씩 늘리고 스캐너가 검색 할 단어가 부족하면 특정 단어가 텍스트 파일에 나타나는 총 횟수를 인쇄합니다.