728x90

✨ 원하는 알파벳이나 숫자(0-9)의 아스키 코드(ASCII Code)를 알고 싶을 때, 사용하는 helper method
(e.g., str.charCodeAt(0)) 왼쪽처럼 알고 싶은 string의 index를 넣어서 사용한다. ()안에 아무것도 넣지 않으면 default 0
백준 11654번: 아스키 코드,  10809번: 알파벳 찾기 문제를 풀 때 사용하였다.

💻Example Code

const str = 'a';
const numStr = '1';

console.log( str.charCodeAt(0) );
console.log( numStr.charCodeAt(0) );
console.log( 'a'.charCodeAt(0) );

실행 결과('a'는 97, '1'은 49, 'A'는 65)

😋 JavaScript에서 string의 ASCII Code를 알고 싶을 때 사용하면 된다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt

 

String.prototype.charCodeAt()

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.indexOf()  (0) 2020.01.01
String.prototype.match()  (0) 2019.12.31
new String()  (0) 2019.12.29
new Array()  (0) 2019.12.29
Array.prototype.메소드() 만들기  (0) 2019.12.29
728x90

https://www.acmicpc.net/problem/11654

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/2c58f2ea15236b75873c5f215996968ebc3c42e3

😢 학부에서 C나 Java를 쓸 때는 자주 사용했던 ASCII Code인데, JavaScript를 주로 사용하게되면서 오랜만에 써보았다.
아니 JavaScript에서는 처음 ASCII Code를 다뤘다.

😊 C나 Java에서는 변환명세 %d, %c 등을 통해 다뤘던 기억이 나는데,
JavaScript에서는 String.charCodeAt(index) helper method를 사용하면 된다.
그리고 4번째 줄에서 trim()도 사용하였지만, 사실 이 문제에서는 굳이 사용하지 않아도 된다.
다른 정답자들도 모두 이 방법으로 풀었다. 다른 방법이 딱히 없나보다.

✔ String.charCodeAt()

String이 담겨있는 변수에 charCodeAt(알고 싶은 index)를 이용해 사용해주면 된다.

Full Code

// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For Local Test
const input = 'A\n';
 
console.log(input.charCodeAt(0));

+ Recent posts