저장을 습관화
프로그래머스 LV.0 문자열안에 문자열 본문
프로그래머스 LV.0 문자열안에 문자열
https://school.programmers.co.kr/learn/courses/30/lessons/120908
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 명
문자열안에 문자열
2. 문제 설명
문자열 str1, str2가 매개변수로 주어집니다. str1 안에 str2가 있다면 1을 없다면 2를 return하도록 solution 함수를 완성해주세요.
3. 제한 사항
- 1 ≤ str1의 길이 ≤ 100
- 1 ≤ str2의 길이 ≤ 100
- 문자열은 알파벳 대문자, 소문자, 숫자로 구성되어 있습니다.
4. 예시
str1 | str | result |
"ab6CDE443fgh22iJKlmn1o" | "6CD" | 1 |
"ppprrrogrammers" | "pppp" | 2 |
"AbcAbcA" | "AAA" | 2 |
5. 기본 제공 코드
function solution(str1, str2) {
var answer = 0;
return answer;
}
6. 제출한 내 답
const solution = (str1, str2) => {
if (str1.match(str2) === null) {
return 2;
} else {
return 1;
}
};
6-2. VSC에 작성한 내용
const solution = (str1, str2) => {
if (str1.match(str2) === null) {
return 2;
} else {
return 1;
}
};
// 테스트
console.log(solution("ab6CDE443fgh22iJKlmn1o", "6CD"));
console.log(solution("ppprrrogrammers", "pppp"));
7. 특이사항
문자열의 메소드 match를 검색해서 적용해 보았다.
설명
let str1 = "ab6CDE443fgh22iJKlmn1o";
let str2 = "6CD";
// str1안에 str2가 포함되어 있다면 아래와 같은 결과가 나온다.
// 찾고 있는 문자열(str2), str1 안에서 str2가 시작되는 위치, 검색하려는 원본
console.log(str1.match(str2)); // [ '6CD', index: 2, input: 'ab6CDE443fgh22iJKlmn1o', groups: undefined ]
// 하지만 str1 안에 str2가 포함되어 있지 않다면 null이 나온다.
let str1 = "ab6CDE443fgh22iJKlmn1o";
let str2 = "aaaa";
console.log(str1.match(str2)); // null
8. 다른 사람이 작성한 답
8-1. split
function solution(str1, str2) {
return str1.split(str2).length > 1 ? 1 : 2
}
설명
// 만약 str2가 str1 안에 포함되어 있다면
// str2를 기준으로 요소 2개를 가지는 배열화 된다.
let str1 = "ab6CDE443fgh22iJKlmn1o";
let str2 = str1.split("6CD");
console.log(str2); // [ 'ab', 'E443fgh22iJKlmn1o' ]
console.log(str2.length); // 2
// str2가 str1 안에 포함되어 있지 않다면
// 배열화는 되더라도 2개 이상으로 쪼개지지는 않는다.
let str1 = "ab6CDE443fgh22iJKlmn1o";
let str2 = str1.split("pppp");
console.log(m); // [ 'ab6CDE443fgh22iJKlmn1o' ]
console.log(m.length); // 1
8-2. include
function solution(str1, str2) {
return str1.includes(str2) ? 1 : 2;
}
function solution(str1, str2) {
if (str1.includes(str2)) {
return 1
} else {
return 2
}
}
'코딩 테스트 > 프로그래머스 - 자바스크립트' 카테고리의 다른 글
프로그래머스 LV.1 가운데 글자 가져오기 (0) | 2023.09.14 |
---|---|
프로그래머스 LV.1 문자열 내 p와 y의 개수 (0) | 2023.09.14 |
프로그래머스 LV.0 모음 제거 (0) | 2023.09.14 |
프로그래머스 LV.0 특정 문자 제거하기 (0) | 2023.09.14 |
프로그래머스 LV.0 문자 반복 출력하기 (0) | 2023.09.14 |