Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

재훈재훈

문자열 다루기 예제 3 - index maker 수정본 본문

Computer Engineering/JAVA

문자열 다루기 예제 3 - index maker 수정본

jaehoonx2 2018. 4. 7. 17:25

소스 출처 - 부경대 권오흠 교수님, <JAVA로 배우는 자료구조> 강의


/*

index maker 수정본

기존 문제점 1. 소수점, 쉼표 등의 특수기호가 단어에 포함된다 

- 해결

기존 문제점 2. 숫자 등이 단어로 취급된다

- 해결

기존 문제점 3. 대문자와 소문자가 다른 단어로 취급된다

- 해결

단어들이 알파벳 순으로 정렬되면 좋겠다

- 삽입정렬 기능 추가

 */


import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Scanner;


public class Code23 {


static String [] words = new String[100000];         // 단어의 갯수

static int [] count = new int[100000];   // 각 단어의 등장 횟수

static int n = 0;   // 저장된 단어 목록의 길이

  // 배열은 자동으로 0으로 초기화됨.

public static void main(String[] args){

Scanner kb = new Scanner(System.in);

while(true){

System.out.print("$ ");

String command = kb.next();             // String을 사용자로부터 입력받음


if(command.equals("read")) {           // string.equals(anotherstr) -> 문자열 일치한지 체크

String fileName = kb.next();

makeIndex( fileName );

}

else if(command.equals("find")){

String str = kb.next();

int index = findWord(str);

if(index > -1) {

System.out.println("The word " + words[index] + " appears " + count[index] + " times.");

}

else

System.out.println("The word " + str + " does not appear.");

}

else if(command.equals("saveas")){

String fileName = kb.next();

saveAs( fileName );

}

else if(command.equals("exit")){

break;

}

}

kb.close();

}

static void makeIndex(String fileName){

//파일을 열어서 읽어야 함

try {

Scanner inFile = new Scanner( new File(fileName));

while(inFile.hasNext()){

String str = inFile.next(); 

String trimmed = trimming(str);

if(trimmed != null){

String t = trimmed.toLowerCase(); // 같은 단어들 다 소문자로 일괄 저장하게 해줌 (기존 문제점 3)

addWord( t ); // 내가 읽은 이 str이 첫 단어인가 이미 찾은 단어인가 확인

}

}

inFile.close();

} catch (FileNotFoundException e) {

System.out.println("No file");

return;

}

}

static String trimming(String str) {        // 기존 문제점 1,2 해결

int i = 0, j = str.length() - 1;

    //while(str.charAt(i) >='a' && str.charAt(i) <= 'z')

    //while i번째 캐릭터가 알파벳이 아닌 동안 계속 반복(밑줄 코드와 같은 의미)

while(i < str.length() && !Character.isLetter( str.charAt(i)) )

//i가 배열 인덱스의 범위를 넘지 않으면서 캐릭터가 알파벳이 아닌 동안 계속 반복해라!

i++;

while(j >= 0 && !Character.isLetter( str.charAt(i)) )

//j가 배열 인덱스의 범위를 넘지 않으면서 캐릭터가 알파벳이 아닌 동안 계속 반복해라!

j--;

// iㅁㅁㅁㅁㅁㅁㅁㅁㅁj -> 순수 알파벳 부분인 i부터 j까지 자르는 것임

if( i>j )

return null; //i와 j가 엇갈림 -> 다 특수문자만 있어서 남는 게 없다!

return str.substring(i,  j+1); // 범위는 [i,j+1)이다! (i<=....<=j) 

}


static void addWord(String str){

int index = findWord(str);  //단어목록에 이 단어가 포함되어 있는지 여부 확인 - 있으면 인덱스 반환, 없으면 -1 return

if(index != -1){            //찾았다(있다) words[index] == str

count[index]++;

}

else{    //못찾았다 - 새로운 단어가 등장한 것임, 뒤에서부터 삽입하면서 정렬 (정렬 기능 추가)

int i = n-1;

for(; i>=0 && words[i].compareToIgnoreCase(str)>0;i--){

words[i+1] = words[i];

count[i+1] = count[i];

}

words[i+1] = str;

count[i+1] = 1;

n++;

}

}

static int findWord(String str){

for(int i=0; i<n; i++)

if(words[i].equalsIgnoreCase((str))) // equalsIgnoreCase 대소문자 무시하고 단어의 일치 유무 확인

return i; //index 반환

return -1; // 찾는 단어가 없음

}

static void saveAs(String fileName) { // 파일 출력 함수

PrintWriter outFile;

try {

outFile = new PrintWriter(new FileWriter(fileName)); // 그냥 외우기

for(int i=0; i<n; i++)

outFile.println(words[i] + " " + count[i]);

outFile.close();

} catch (IOException e) {

System.out.println("Save failed");

return;

}

}

}