Study/JS Algorithm Rocket
[JS] 기초 (2) - 문자대체, 찾기, 개수, 중복제거, 대소문자 변환
이안92
2021. 5. 17. 15:40
반응형
문자대체
.replace(/원래문자/, '변경할문자');
<script>
function solution(s){
// 첫번째 방법
let answer="";
for (let x of s){
if(x==='A') answer+='#';
else answer+=x;
}
return answer;
}
let str="BANANA";
console.log(solution(str));
</script>
<script>
function solution(s){
// 두번째 방법
let answer=s;
answer=answer.replace(/A/g, '#'); // g 전역
return answer;
}
let str="BANANA";
console.log(solution(str));
</script>
문자찾기
.split(a) a에 해당하는 문자를 잘라낸다
<script>
function solution(s, t){
// 첫번째 방법
let answer=0;
for(let x of s){
if(x===t) answer++;
}
return answer;
}
let str="COMPUTERPROGRAMMING";
console.log(solution(str, 'R'));
</script>
<script>
function solution(s, t){
// 두번째 방법
let answer=s.split(t).length; // (4) ["COMPUTE", "P", "OG", "AMMING"]
return answer-1; // 마지막 문자여도 "" 빈 문자열이 들어가므로 동일하다
}
let str="COMPUTERPROGRAMMING";
console.log(solution(str, 'R'));
</script>
대문자찾기
.toUpperCase() 대문자로 변경
.charCodeAt() ASCII코드로 변경. 대문자 65~90, 소문자 97~122
<script>
function solution(s){
let answer=0;
// 첫번째 방법
for(let x of s){
if(x===x.toUpperCase()) answer++; // K === K, o === O, r === R...
}
return answer;
}
let str="KoreaTimeGood";
console.log(solution(str));
</script>
<script>
function solution(s){
let answer=0;
// 두번째 방법
for(let x of s){
let num=x.charCodeAt(); // ASCII코드 대문자 65~90 소문자 97~122
if(num>=65 && num<=90) answer++;
}
return answer;
}
let str="KoreaTimeGood";
console.log(solution(str));
</script>
대문자로 통일
<script>
function solution(s){
let answer="";
// 첫번째 방법
for(let x of s){
if(x===x.toLowerCase()) answer+=x.toUpperCase(); //소문자면 대문자로 바꿈
else answer+=x;
}
return answer;
}
let str="ItisTimeToStudy";
console.log(solution(str));
</script>
ASCII 소문자 a 97, 대문자 A 65. 차이는 32
<script>
function solution(s){
let answer="";
// 두번째 방법 ASCII
for(let x of s){
let num=x.charCodeAt(); // String.fromcharCode()는 괄호안을 문자열로 반환한다
if(num>=97 && num<=122) answer+=String.fromCharCode(num-32);
else answer+=x;
}
return answer;
}
let str="ItisTimeToStudy";
console.log(solution(str));
</script>
대소문자 변환
.toUpperCase()
.toLowerCase()
<script>
function solution(s){
let answer="";
for(let x of s){
if(x===x.toUpperCase()) answer+=x.toLowerCase();
else answer+=x.toUpperCase();
}
return answer;
}
console.log(solution("StuDY"));
</script>
가장 긴 문자열
Number.MIN_SAFE_INTEGER 최대값을 찾기위해 먼저 가장 작은 정수로 잡는다.
<script>
function solution(s){
let answer, max=Number.MIN_SAFE_INTEGER;
for(let x of s){
if(x.length>max){
max=x.length;
answer=x;
}
}
return answer;
}
let str=["teacher", "time", "student", "beautiful", "good"];
console.log(solution(str));
</script>
가운데 문자 출력
Math.floor() 소수점 내림, 나눈 몫 구하기
.substring(2, 4) : 2번 인덱스부터 3번 인덱스까지. length => ng
.substr(2, 4) : 2번 인덱스부터 4개 뽑아냄. length => ngth
s.substring(mid, mid+1) => s.substr(mid, 1);
s.substring(mid-1, mid+1) => s.substr(mid-1, 2);
<script> // good이면 oo, top 이면 o
function solution(s){
let answer;
let mid=Math.floor(s.length/2); // 단어를 길이를 2로 나눈 몫 floor는 내림 (소수점 날림)
if(s.length%2==1) answer=s.substring(mid, mid+1); // 홀수일 때 mid부터 mid+1 전까지
else answer=s.substring(mid-1, mid+1); // 짝수일 때 4/2 good는 두번째 o가 2번째
return answer;
}
console.log(solution("study"));
</script>
중복문자 제거
.indexOf('k') : 처음 발견하는 곳 -> 위치 0
.indexOf('k', 1) : 1번부터 찾아라 -> 위치 3
<script>
function solution(s){
let answer="";
for(let i=0; i<s.length; i++){
console.log(s[i], i, s.indexOf(s[i]));
// k 0 0, s 1 1, e 2 2, k 3 0, k 4 0, s 5 1, e 6 2, t 7 7
if(s.indexOf(s[i])===i) answer+=s[i];
// 최초의 문자 인덱스번호와 본래 위치가 일치할 때 첫번째로 발견된 것
}
return answer;
}
console.log(solution("ksekkset")); //kset
</script>
특정문자 개수
.indexOf('K') : 발견못할 때 -> 위치 -1
<script>
function solution(s){
let answer=0;
let pos=s.indexOf('k');
console.log(s.indexOf('k')); // 0
while(pos!==-1){ // indexOf()가 -1면 찾지 못한것이므로 특정문자 찾았을때 반복문
console.log(pos); // 0, 3, 4
answer++; // 찾으면 카운팅
pos=s.indexOf('k', pos+1); // pos 첫번째 찾은 그 위치 뒷편부터 찾아라
}
return answer;
}
console.log(solution("ksekkset"));
</script>
중복단어 제거
.filter() 배열 filter함수 조건만족하는 것만 return받아서 새로운 배열을 만듦
s.filter((v, i) => {}) : v는 s라는 배열의 값들, i는 인덱스
<script>
function solution(s){
let answer;
console.log(s.indexOf("good")); // 0, "time"은 1, "student"는 4
answer=s.filter((v, i) => {
console.log(v, i); // good 0, time 1, good 2, time 3, student 4
if(s.indexOf(v)===i) return v; // 일치하면 처음 나온 것
});
return answer;
}
let str=["good", "time", "good", "time", "student"];
console.log(solution(str));
</script>
반응형