하고 싶은게 많음

프로그래머스 - 문자열 정렬하기 본문

IT

프로그래머스 - 문자열 정렬하기

쏘매띵 2023. 9. 30. 17:29

문자열 정렬하기

https://school.programmers.co.kr/learn/courses/30/lessons/120850?language=javascript 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

접근 방법: 반복문(for of)을 이용 -> isNaN을 이용해 숫자인 것을 if문으로 검색하여 sum배열에 저장 -> sort를 사용하여 오름차순 정렬

- isNaN() :괄호 안 매개변수가 숫자인지 판별하는 메소드. (매개변수 숫자면 false , 숫자가 아니면 true 반환)

function solution(my_string) {
    let sum = [];
    for (const ch of my_string) {
        if (!isNaN(ch)) 
            sum.push(Number(ch));
    }
    return sum.sort((a,b)=>a-b);
}

 

 


 

다른 사람 풀이

1. match : 특정 문자열 안에서 검색할 문구가 포함되어 있는지 확인 가능

사용법 : 해당 문자열. match('검색할 단어');

var str = 'Hello World...!'

console.log(str.match('World')); 
// 결과값:  [ 'World', index: 6, input: 'Hello World...!', groups: undefined ]
console.log(str.match('haha')); 
// 결과값: null

 

+ ) match + 정규표현식 ( g  와 i ) : g와 i 를 사용하여 대소문자 구분없이 match함수가 전체 적용이 가능하도록 할 수 있음.

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
// 결과값 : ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

 

2. 정규 표현식 (\d ): 숫자만 검색함. [0-9]로도 사용가능.

3. sort () 정렬

.sort((a, b) => a - b); //오름차정렬
.sort((a, b) => b - a); //내림차정렬

 

4. map( )

//배열에 들어있는 숫자들의 제곱근을 구하여 새로운 배열을 만들기
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots는 [1, 2, 3]
// numbers는 그대로 [1, 4, 9]

 

 

 


[참고 자료]

match( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

 

String.prototype.match() - JavaScript | MDN

The match() method of String values retrieves the result of matching this string against a regular expression.

developer.mozilla.org

 

 

정규 표현식 (/g, /i, /d)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes

 

Character classes - JavaScript | MDN

Character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.

developer.mozilla.org

 

map( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

Array.prototype.map() - JavaScript | MDN

The map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.

developer.mozilla.org

 

Comments