자바8의 유용한 클래스와 메소드들

kdkdhoho·2022년 1월 21일
1

String 클래스

substring()

String substring(int beginIndex): 문자열의 beginIndex부터 끝까지 반환
String substring(int beginIndex, int endIndex): 문자열의 beginIndex부터 endIndex - 1까지 반환

public class Main {
	public static void main(String[] args) {
		String str = "abcdefg";
		
		String str1 = str.substring(4);
		String str2 = str.substring(0, 4);
		
		System.out.println(str1);
		System.out.println(str2);
	}
}

efg
abcd

charAt()

char charAt(int index): 문자열 중 index에 있는 문자 하나를 반환한다.

public class Main {
	public static void main(String[] args) {
		String str = "abcdefg";
		
		char chr = str.charAt(str.length() - 1);
		System.out.println(chr);
	}
}

g

indexOf()

int indexOf(String str): 문자열 중 str이 나오는 첫 index를 반환한다. 만약, 탐색에 실패하면 -1 을 반환한다.
int indexOf(String str, int fromIndex): 문자열 중 fromIndex부터 탐색을 시작하여 전체 문자열 중 str이 나오는 첫 index를 반환한다. 만약, 탐색에 실패하면 -1 을 반환한다.

public class Main {
	public static void main(String[] args) {
		String str = "abcdefg hi";
		
		int index = str.indexOf("a");
		System.out.println(index);
		
		index = str.indexOf("hi");
		System.out.println(index);
		
		index = str.indexOf("d", 0);
		System.out.println(index);
		
		index = str.indexOf("j");
		System.out.println(index);
	}
}

0
8
3
-1

split()

String[] split(String regex): 문자열을 regex를 기준으로 각각 나누어 String 배열로 반환한다.

public class Main {
	public static void main(String[] args) {
		String str = "abcdefg hi";
		
		String[] result = str.split(" ");
		for(String s : result)
			System.out.print(s + ", ");
	}
}

abcdefg, hi,

또 다른 예로 뒤에 나올 Scanner 클래스와 연계하여

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		String[] arr = sc.nextLine().split(" ");
		for(String s : arr)
			System.out.print(s + " ");
	}
}

한 줄에 여러 문자를 공백을 기준으로 입력받을 때 String[] arr = sc.nextLine().split(" "); 이렇게도 사용할 수 있다.

Collections 클래스

max()

<T extends Object & Comparable<? super T>> T max​(Collection<? extends T> coll): 주어진 Collection 중 가장 큰 값을 반환한다.

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Integer[] list = {1, 2, 3, 4, 5};
		ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(list));
		
		int max = Collections.max(arr);
		System.out.println(max);
	}
}

5

min()

<T extends Object & Comparable<? super T>> T min​(Collection<? extends T> coll): 주어진 Collections 중 가장 작은 값을 반환한다.

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Integer[] list = {1, 2, 3, 4, 5};
		ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(list));
		
		int min = Collections.min(arr);
		System.out.println(min);
	}
}

1

sort()

<T extends Comparable<? super T>> void sort​(List<T> list): 주어진 List를 오름차순으로 정렬하여 반환한다.

import java.util.*;

public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> arr = new ArrayList<>();
		arr.add(3);
		arr.add(2);
		arr.add(1);

		System.out.println(arr);
		
		Collections.sort(arr);
		System.out.println("After Sorting: " + arr);
	}
}

[3, 2, 1]
After Sorting: [1, 2, 3]

reverse()

void reverse(List<?> list): 주어진 List를 역순으로 바꿔준다.

import java.util.*;

public class Main {
	public static void main(String[] args) {
		ArrayList<Integer> arr = new ArrayList<>();
		arr.add(10);
		arr.add(1);
		arr.add(5);

		System.out.println(arr);
		
		Collections.reverse(arr);
		System.out.println("After Reversing: " + arr);
	}
}

[10, 1, 5]
After Reversing: [5, 1, 10]

Scanner 클래스

next() vs nextLine()

  • String next(): 다음 토큰을 문자열로 리턴한다.
  • String nextLine(): \n을 포함하는 한 라인을 읽고, \n을 버린 나머지를 리턴한다.

둘의 차이점은 개행 문자 즉, \n을 포함하냐 안하냐이다.

입력을
123
456
이라고 했을 때, 현재 입력버퍼에는 123/\n/456/\n이 들어가있다.

next()의 경우 첫 \n 전까지인 123만 읽을 것이고,
그 다음 바로 nextLine()을 할 경우 버퍼의 맨 앞에 있는 \n만을 읽어 값을 제대로 읽어오지 못한다.

// 잘못된 예시
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		String a = sc.next();
		String b = sc.nextLine();
		
		System.out.println(a + " " + b);
	}
}

123

이럴 경우엔 \n만을 제거해주기 위해 중간에 nextLine()을 하나 추가해준다.

// 고친 예시
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		String a = sc.next();
		sc.nextLine();
		String b = sc.nextLine();
		
		System.out.println(a + " " + b);
	}
}

123 456

nextInt()나 nextFloat()도 next()와 마찬가지로 \n 전까지만 읽어온다.

profile
newBlog == https://kdkdhoho.github.io

0개의 댓글