한 걸음 두 걸음

java 자바 문자열 관련 모아놓자 본문

Language/Java

java 자바 문자열 관련 모아놓자

언제나 변함없이 2019. 2. 18. 14:43
반응형

0. String / StringBuilder / StringBuffer중 필요한 Class 선정 후 사용

String : 변경되지 않는 문자열 연산에 적합. 멀티스레딩 safe

StringBuffer : 멀티 쓰레드용(동기) 자주 변경되는 문자열

StringBuilder : 단일스레드용(비동기) 자주 변경되는 문자열

* stringBuilder 함수 사용 참고링크 http://www.dreamy.pe.kr/zbxe/CodeClip/158356

https://docs.oracle.com/javase/8/docs/api/

(stringBuilder -> string으로 바꿀 때 toString사용)

---String기준---

1. 문자열 입력받기

1.1 next()함수

개행문자를 무시하고 띄어쓰기 혹은 엔터직전까지 입력을 받는다. 

Scanner sc = new Scanner(System.in);
String str; 있으면
str = sc.next();

1.2 nextLine()함수

개행문자까지 입력을 받는다.

Scanner sc = new Scanner(System.in);
String str; 있으면
str = sc.nextLine();

1.3 hasNext()함수

  while(sc.hasNext()) {
                System.out.println(sc.next()); }

hasNextInt 등으로 세분화되어있음

2. 문자열 합치기

2.1 +연산자 사용하기

String a , b 있으면 a+b해준다.

2.2 concat함수 사용하기

a.concat(b);

2.3 append함수 사용하기

-> 대신 +연산자 사용해주는게 더 좋을 것 같긴하다.
StringBuilder sb = new StringBuilder("텍스트");
sb.append("추가1");
sb.append("추가2");

참고 URL : https://coding-factory.tistory.com/127

3. 문자열 나누기

3.1 split()함수 사용하기

String[] word = alltxt.split("@");
word[0] word[1]으로 @를 기준으로 쪼개어 들어가진다.

substring(int);
int index부터 끝까지 잘라서 String반환
substring(int, int)
int 부터 int까지 index잘라서 String반환

3.2 subString()함수 사용하기

    String exStr = "aabbaccc"; //길이: 8 요소인덱스 :0,1,2,3,4,5,6,7

        System.out.println(exStr.substring(0, 3)); //0,1,2 요소를 잘라 반환합니다.
        System.out.println(exStr); //잘라서 반환할 뿐, 실제 메모리상 문자열이 제거되지 않습니다.

        for(int i = 1 ; i <= exStr.length()/2; i++) {
            System.out.println(exStr.substring((i-1)*2 , i*2));
        }


4. 파일 입출력

4.1 스트림

입출력 스트림에는 바이트 스트림과 문자 스트림이 있다. (import java.io.*)
바이트 스트림은 바이트 단위로 입출력을 진행하며 주로 이진 데이터를 읽고 쓰기 위하여 사용된다.(InputStream / OutputStream)
문자 스트림은 문자 단위(유니코드)로 입출력이 진행된다. (Reader / Writer)

텍스트파일을 복사하는 것은 문자 스트림이 더 적절하다.
바이트 스트림은 기초적인 입출력에만 사용됨.

바이트스트림
FileInputStream FileOutputStream클래스를 이용한다.

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

public class Main {
    public static void main(String[] args) throws IOException{
        FileInputStream in = null;
        FileOutputStream out = null;

        try{
        in = new FileInputStream("input.txt");
        out = new FileOutputStream("output.txt");

        int c;

        while((c = in.read()) != -1) out.write(c);
        }finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
        }

        System.out.println("완료");


    }    

}

이처럼 바이트를 읽을 땐 read()함수를, 쓸 때는 write함수를 사용한다.(read함수는 int로 반환한다.)

문자 스트림
FileReader와 FileWriter 클래스를 활용한다.

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

public class Main {
    public static void main(String[] args) throws IOException{
        FileReader in = null;
        FileWriter out = null;

        try{
        in = new FileReader("input.txt");
        out = new FileWriter("output.txt");

        int c;

        while((c = in.read()) != -1) out.write(c);
        }finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
    }}    }

읽을 땐 read() 쓸 땐 write()함수 사용합니다.


** 문자단위가 아닌 한 줄 단위로 입출력을 진행하는 경우**
BufferedReader와 PrinterWriter 클래스를 활용합니다.

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

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader in = null;
        PrintWriter out = null;

        try{
        in = new BufferedReader(new FileReader("input.txt"));
        out = new PrintWriter(new FileWriter("output.txt"));

        String c;

        while((c = in.readLine()) != null) out.println(c);
        }finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }}}
          }

이는 BufferedReader가 FileReader로부터 얻은 data를 \n단위로 쪼개서 출력하는 것이다.

4.2 버퍼 스트림

파일 입출력을 요청 할 때마다 디스크로 가서 파일을 읽어오는데 이는 굉장히 비효율적인 방법이기 때문에 사용할 문자의 많은 부분을 buffer에 미리 다 읽어놓고 나중에 buffer가 비었을 때만 다시 디스크에 접근하는 방법을 사용합니다. (마찬가지로 buffer에 다 write해두었다가 더 이상 공간이 없으면 디스크에 갖다놓습니다.)

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

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader in = null;
        BufferedWriter out = null;

        try{
        in = new BufferedReader(new FileReader("input.txt"));
        out = new BufferedWriter(new FileWriter("output.txt"));

        String c;

        while((c = in.readLine()) != null) out.write(c);
        }finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }    }    }    }

이처럼 버퍼 스트림은
바이트스트림에 적용시킬 수 있는 BufferedInputStream / BufferedOutputStream
문자스트림에 적용시킬 수 있는 BufferedReader / BufferedWriter
가 제공된다.

버퍼를 수동으로 비우기 위해서는 flush()함수를 사용합니다

4.3 File 클래스 활용하기

File 클래스를 활용합니다. File file = new File("파일이름.txt");
-> File 내부의 메소드

boolean canExecute() 파일을 실행할 수 있는지 확인
boolean canRead() 파일을 읽을 수 있는지 확인
boolean delete() 파일 삭제하기
boolean exists() 파일 || 디렉토리의 존재여부 확인
boolean isDirectory() 디렉토리가 있는지 확인
boolean isFile() 파일이 있는지 확인
boolean canWrite() 파일 변경 가능한지 확인
boolean mkdir() 디렉토리를 생성
boolean renameTo(File) 파일 이름 변경
boolean setExecutable(boolean) 파일 실행 가능하게 설정
boolean setLastModified(long) 파일이 수정된 변경 날짜를 설정합니다.

String getAbsolutePath() 절대 경로 반환
String getName() 파일의 이름
String getParent() 부모의 경로 이름
String[] list() 디렉토리 안에 포함된 파일과 디렉토리를 반환

File getParentFile() 부모파일 반환
File createTempFile(String, String) 임시 파일 생성

사용예시
File file = new File("file.txt");
if(file.isFile()){}

4.4 문자열 formating

java에서 입력을 받을 때 주로
Scanner sc = new Scanner(System.in);
이런식으로 Scanner 클래스를 사용하는데,
이는 공백문자(띄어쓰기, 탭, 엔터) 등을 기준으로 각각의 토큰을 분리시키는 기능을 가지고 있다.
하지만 토큰을 분리시키는 기준으로 공백문자를 사용하고 싶지 않다면 sc.useDlimiter("해당문자"); 를 사용하여 별도로 지정해줄 수 있다.

public class Main {
    public static void main(String[] args)throws IOException{
        Scanner sc = null;
        try {
            sc = new Scanner(new BufferedReader(new FileReader("input.txt")));

            while(sc.hasNext()) {
                System.out.println(sc.next());
            }
        }finally {
            if(sc != null) sc.close();
        }}}

input.txt파일을 따로 두었는데, 이 파일을 읽어서 다음 문자가 있다면 이를 단어단위(next())로 출력하는 프로그램이다.

5. 변환

5.1 Int <-> String

int -> Stirng ] String.valueOf(count);
Integer.toString(count);
String -> int ] Integer.parseInt(mumja);

//기타 자동줄바꿈 : control+shift+f

6. 참고URL

JAVA 입출력의 다양한 형태 (대회에서 활용하는 방법 등) https://seonghui.github.io/java-plang-1/#link-1-3

[

dev.log – Stella Seonghui Yu

Stella Seonghui Yu

seonghui.github.io

](https://seonghui.github.io)

Scanner sc = new Scanner(System.in);

sc.nextInt(); //등으로 하고 입력을 다 받은 후에는

sc.close(); //로 자원사용을 close해주면 더욱 좋습니다 : )

반응형

'Language > Java' 카테고리의 다른 글

JAVA 자바 특징  (0) 2019.11.14
JAVA Refactor Rename + 단축키  (0) 2019.10.17
java 자바 ] arrayList  (0) 2019.06.12
JAVA Queue Collection 큐 사용하기  (0) 2019.05.27
JAVA final의 사용  (0) 2019.04.07