문자열 조작

코딩 인터뷰 중에 문자열 조작과 관련된 많은 문제가 발생합니다. 이 기사에서는 코딩 인터뷰에 유용할 수 있는 몇 가지 문자열 방법을 검토하고 싶습니다.

문자열 길이




str.length


액세스 캐릭터



인덱스로 특정 문자 찾기




let str = hello world;
console.log(str.charAt(0));
console.log(str[0]);

// both above’s result are the same: h


문자 또는 문자열이 존재합니다.




let str = hello world;
// true
console.log(str.includes(he);
// true
console.log(str.includes(l));
// false
console.log(str.includes(x);

indexOf()를 사용하여 문자열이나 char이 문자열에 존재하는지 찾을 수도 있습니다. 존재하는 경우 문자 인덱스를 반환합니다(문자열(예: "el")을 사용하는 경우 문자열의 첫 번째 문자 인덱스를 얻음). 존재하지 않으면 -1을 반환합니다. 알다시피 indexOf()는 문자열에서 문자의 인덱스를 찾는 데 사용할 수 있습니다.

문자 바꾸기




let str = hello world;
// this will replace char ‘o’ to ‘l’
str.replace(o, l);
// this will remove empty space 
str.replace( , “”);


문자를 특정 인덱스로 교체할 수도 있습니다. 그런 다음 .substr() 를 사용하여 다음 함수를 만듭니다.

const replaceAt = (index, str, rep) => {
  return str.substr(0, index) + rep + str.substr(index + rep.length); 
};



문자 제거



문자열에서 특정 문자를 제거하려면 replace() 메서드를 사용하여 일치하는 모든 문자를 제거할 수 있습니다. 그러나 대부분의 경우 특정 인덱스가 있는 특정 문자를 제거하려고 할 수 있습니다. 이 경우 두 가지 다른 방법을 사용할 수 있습니다.

하위 문자열 사용

let str = hello world;

const removeChar = (str, index) => {
  str.substring(0, index) + str.substring(index + 1);
};

// this will result “helo world”
console.log(removeChar(str, 3));



슬라이스 사용

let str = hello world;

const removeChar = (str, index) => {
  return str.slice(0, index) + str.slice(index + 1, str.length);
};

// this will result “helo world”
console.log(removeChar(str, 3));


문자열을 숫자로




// 2
parseInt(2);
// 2.0
parseFloat(2.0);


소문자/대문자 문자열




// he
str.toLowerCase(“HE”);

// HE
str.toUpperCase(“he”);


배열로 변환



때로는 배열 함수를 사용하기 위해 문자열을 배열로 변환해야 할 수도 있습니다. 이렇게 하려면 네 가지 옵션을 사용할 수 있습니다.

let str = hello world;
// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
str.split(“”);
// [“hello”, “world”];
str.split( );

// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
[str];

// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
Array.from(str);

// [“h”, “e”, “l”, ”l”, “o”, “ “, “w”, “o”, “r”, “l”, “d”]
Object.assign([], str);



루프를 사용하여 A에서 Z까지의 문자 배열 생성




const atoz = [];
// this will give A to Z (upper case alphabets)
for(let i =0; i < 26; i+=1) {
  atoz.push(String.fromCharCode(65 + i));
}

// this will give a to z (lower case alphabets)
for(let i =0; i < 26; i+=1) {
  atoz.push(String.fromCharCode(97 + i));
}

좋은 웹페이지 즐겨찾기