728x90

Q. 주어진 String(문장)에서 각 단어의 첫 알파벳을 대문자로 바꿔라.

--- Examples
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/08ffc38c2f7b32b8baa35a6ecfc6c1d367559b1c/exercises/capitalize/index.js

😢 배열(Array)의 index을 이용해서 원초적 해결하려 했더니 조금 힘들었다.

😊 Solution 1)
입력받은 str을 split(' ')을 이용해 각 단어별로 나눠진 Array를 만들어주고,
for ... of loop 안에서 각 단어를 하나씩 가져와, 첫 번째 알파벳은 대문자로, 나머지 값은 slice(1)로 붙여주었다.
그리고 join(' ')을 이용해 다시 String(문장)으로 만들어 반환해주었다.

Solution 2)
classic for loop을 이용해 각 index의 앞(i-1)이 ' '(space)라면 해당 index(i)를 대문자로 변환하여 저장한다.
그게 아니라면, 해당 index(i)를 단순 저장해준다.

✔ toUpperCase()

소문자를 대문자로 변환해준다.

✔ split(' ')

String을 ' '(space)기준으로 나눠서 array에 저장해준다

✔ slice(1)

index 1부터 끝까지 모두 slice해준다

✔ for ... of

Array의 안에 있는 값을 index 순서대로 하나씩 가져온다

✔ join(' ')

' '(space)기준으로 Array를 String(문장)으로 합쳐준다

Full Code

function capitalize(str) {
let result = str[0].toUpperCase();
 
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === ' ') {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
 
return result;
}
 
// function capitalize(str) {
// const words = [];
 
// for (let word of str.split(' ')) {
// words.push(word[0].toUpperCase() + word.slice(1));
// }
 
// return words.join(' ');
// }
728x90

✨ String의 알파벳을 대문자(toUpperCase()) 또는 소문자(toLowerCase())로 바꿔주는 helper method

(e.g., str.toLowerCase() or str.toUpperCase()) 왼쪽처럼 String 변수에 helper method를 붙여 사용한다.

💻Example Code

const strOne = 'abc';
const strTwo = 'ABC';

console.log( strOne.toUpperCase() );
console.log( strTwo.toLowerCase() );

실행 결과(소문자는 대문자로, 대문자는 소문자로 바뀐 걸 볼 수 있다)

😋 Anagrams(철자 순서를 바꾼 말)와 Vowels(모음 찾기) Algorithm 에서 유용하게 사용했다. 다양한 곳에서 활용이 가능하다.
활용된 내용은 위의 알고리즘 문제를 참고하시면 좋습니다.

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

 

String.prototype.toLowerCase()

The toLowerCase() method returns the calling string value converted to lower case.

developer.mozilla.org

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

 

String.prototype.toUpperCase()

The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).

developer.mozilla.org

 

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

Object.keys() & Object.values()  (0) 2019.12.29
Array.prototype.sort()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24

+ Recent posts