백준 문제를 풀다보면 trim() 함수를 입력값 받을 때 많이 사용하는데, 가끔 입력값을 다룰 때 문자열 함수인 trim()을 넣지 않으면 에러가 난다. 왜 에러가 날까?
먼저, trim() 함수의 사용법에 대해 알아보자.
trim() : 여러 줄의 입력값을 받을 땐 맨 앞과 맨 뒷 공백만 없애준다.
아래 코드를 보고 trim() 함수를 이해해보자.
// 한줄의 경우
const str1 = ' Hello, world! ';
console.log(str1.trim()); // Hello, world;
// 여러 줄의 경우
const str2 = ` hello, world!
i'm sooyeon ! `
console.log(str2.trim());
//hello, world!
//i'm sooyeon !
위의 코드와 같이 trim()은 문자열 양 끝 공백 + 개행문자 들을 지우기 위해 사용한다.
의문점
근데 백준 문제를 풀때 어떤 문자열에는 trim() 함수를 넣어줘야 에러가 안나고, 어떤 문자열에는 trim()함수를 안넣어줘도 에러가 안날까? 라는 생각이 들었다.
이유 !
백준 문제들을 풀때 일부 입력값의 마지막에 개행문자가 포함된 경우가 종종있다.
const str3 = ' 1\r\n2\r\n3\n'
console.log(str3.split('\n')); // [ ' 1\r', '2\r', '3', '' ]
console.log(str3.trim().split('\n')); // [ '1\r', '2\r', '3' ]
만약 개행문자가 포함되어 문자열을 다루게 된다면,
첫번째 console.log에 있는 배열처럼 공백 문자 하나를 더 갖는 배열을 반환하게 된다.
이를 방지하기 위해 trim()을 사용하는 것이다.
'Javascript' 카테고리의 다른 글
[Javascript] 배열 고차 함수 reduce()에 대해 (1) | 2024.06.19 |
---|---|
[Javascript] Map 객체 (0) | 2024.04.03 |
[Web, React] 마우스 휠 가로 스크롤 작동 구현하기 (0) | 2024.03.29 |
[비동기 HTTP 통신] Ajax, Axios, Fetch에 대해 (1) | 2024.03.13 |