itsource

반복 문자로 채워진 가변 길이의 문자열을 만듭니다.

mycopycode 2022. 9. 16. 23:10
반응형

반복 문자로 채워진 가변 길이의 문자열을 만듭니다.

그래서 다른 누군가가 자바 폼에서 질문을 했습니다.Java - 지정된 길이로 특정 문자로 채워진 새로운 String 인스턴스를 만듭니다. 최적의 솔루션?

. . . 단, 동등한 JavaScript를 찾고 있습니다.

기본적으로 각 필드의 "max length" 속성에 따라 텍스트 필드에 "#" 문자를 동적으로 입력합니다.즉, 입력이 다음과 같은 경우maxlength="3"필드에는 "###"이 입력됩니다.

이상적으로는 자바와 같은 것이 있을 것이다.StringUtils.repeat("#", 10);단, 지금까지 생각할 수 있는 최선의 옵션은 최대 길이에 도달할 때까지 루프 스루와 "#"자를 한 번에 하나씩 추가하는 것입니다.나는 그것보다 더 효율적인 방법이 있다는 느낌을 떨칠 수 없다.

좋은 생각 있어요?

참고로 입력에 디폴트값을 설정할 수 없습니다.왜냐하면, 「#」문자는 포커스에서 클리어 할 필요가 있어, 유저가 값을 입력하지 않은 경우는, 「리필」할 필요가 있기 때문입니다.제가 우려하는 것은 '리필' 단계입니다.

이렇게 하는 가장 좋은 방법은

var str = new Array(len + 1).join( character );

그러면 지정된 길이의 배열이 생성된 후 지정된 문자열과 결합되어 반복됩니다..join()함수는 요소에 값이 할당되어 있는지 여부에 관계없이 배열 길이를 준수하며 정의되지 않은 값은 빈 문자열로 렌더링됩니다.

구분 문자열이 배열 요소 사이에 있으므로 원하는 길이에 1을 추가해야 합니다.

시험해 보세요.p

s = '#'.repeat(10)

document.body.innerHTML = s

ES2015에서 가장 쉬운 방법은 다음과 같은 작업을 수행하는 것입니다.

'X'.repeat(data.length)

X어떤 문자열이든data.length원하는 길이입니다.

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

아쉽게도 어레이는.여기서 설명하는 join 접근법은 간단하며 문자열 연결 기반 구현보다 약 10배 느립니다.특히 큰 줄에서는 성능이 떨어집니다.퍼포먼스의 상세한 것에 대하여는, 이하를 참조해 주세요.

Firefox, Chrome, Node.js MacOS, Node.js Ubuntu 및 Safari에서 테스트한 가장 빠른 구현은 다음과 같습니다.

function repeatChar(count, ch) {
    if (count == 0) {
        return "";
    }
    var count2 = count / 2;
    var result = ch;

    // double the input until it is long enough.
    while (result.length <= count2) {
        result += result;
    }
    // use substring to hit the precise length target without
    // using extra memory
    return result + result.substring(0, count - result.length);
};

이 방법은 상세하기 때문에 간단한 구현을 원하는 경우 간단한 접근방식을 사용할 수 있습니다.어레이보다 2배~10배 퍼포먼스가 뛰어납니다.또한 소규모 입력에 대한 2배 이상의 구현 속도보다 빠릅니다.코드:

// naive approach: simply add the letters one by one
function repeatChar(count, ch) {
    var txt = "";
    for (var i = 0; i < count; i++) {
        txt += ch;
    }
    return txt;
}

상세 정보:

상수 문자열을 만들고 그 위에 서브스트링을 호출합니다.

뭐랄까

var hashStore = '########################################';

var Fiveup = hashStore.substring(0,5);

var Tenup = hashStore.substring(0,10);

조금 더 빨리.

http://jsperf.com/const-vs-join

은 ES6를 사용하는 입니다.padStart다음과 같이 합니다.

var str = ''.padStart(10, "#");

주의: IE에서는 (폴리필이 없으면) 동작하지 않습니다.

모든 브라우저에서 작동하는 버전

이 함수는 사용자가 원하는 작업을 수행하며 승인된 답변에서 제시된 옵션보다 훨씬 빠르게 수행됩니다.

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i <= count;)
        array[i++] = str;
    return array.join('');
}

다음과 같이 사용합니다.

var repeatedCharacter = repeat("a", 10);

이 기능의 성능을 승인된 답변에서 제안된 옵션의 성능과 비교하려면 이 바이올린과 바이올린을 참조하여 벤치마크를 확인하십시오.

최신 브라우저 전용 버전

최신 브라우저에서는 다음 작업도 수행할 수 있습니다.

var repeatedCharacter = "a".repeat(10) };

이 옵션은 훨씬 더 빠릅니다.그러나 안타깝게도 어떤 버전의 Internet Explorer에서도 작동하지 않습니다.

이 표의 숫자는 이 방식을 완전히 지원하는 첫 번째 브라우저 버전을 나타냅니다.

여기에 이미지 설명 입력

For Evergreen browsers, this will build a staircase based on an incoming character and the number of stairs to build.
function StairCase(character, input) {
    let i = 0;
    while (i < input) {
        const spaces = " ".repeat(input - (i+1));
        const hashes = character.repeat(i + 1);
        console.log(spaces + hashes);
        i++;
    }
}

//Implement
//Refresh the console
console.clear();
StairCase("#",6);   

또한 이전 브라우저의 Repeat에 대한 폴리필을 추가할 수 있습니다.

    if (!String.prototype.repeat) {
      String.prototype.repeat = function(count) {
        'use strict';
        if (this == null) {
          throw new TypeError('can\'t convert ' + this + ' to object');
        }
        var str = '' + this;
        count = +count;
        if (count != count) {
          count = 0;
        }
        if (count < 0) {
          throw new RangeError('repeat count must be non-negative');
        }
        if (count == Infinity) {
          throw new RangeError('repeat count must be less than infinity');
        }
        count = Math.floor(count);
        if (str.length == 0 || count == 0) {
          return '';
        }
        // Ensuring count is a 31-bit integer allows us to heavily optimize the
        // main part. But anyway, most current (August 2014) browsers can't handle
        // strings 1 << 28 chars or longer, so:
        if (str.length * count >= 1 << 28) {
          throw new RangeError('repeat count must not overflow maximum string size');
        }
        var rpt = '';
        for (;;) {
          if ((count & 1) == 1) {
            rpt += str;
          }
          count >>>= 1;
          if (count == 0) {
            break;
          }
          str += str;
        }
        // Could we try:
        // return Array(count + 1).join(this);
        return rpt;
      }
    } 

Hogan과 Zero Trick Pony의 답변을 바탕으로 합니다.대부분의 사용 사례를 잘 처리할 수 있을 만큼 빠르고 유연해야 한다고 생각합니다.

var hash = '####################################################################'

function build_string(length) {  
    if (length == 0) {  
        return ''  
    } else if (hash.length <= length) {  
        return hash.substring(0, length)  
    } else {  
        var result = hash  
        const half_length = length / 2  
        while (result.length <= half_length) {  
            result += result  
        }  
        return result + result.substring(0, length - result.length)  
    }  
}  

원하는 경우 함수의 첫 번째 줄을 원라이너로 사용할 수 있습니다.

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}

하고 싶다

Buffer.alloc(length, character).toString()

필요한 퍼포먼스라면 (ES6보다 이전)기판과 템플릿스트링을 조합하는 것이 가장 좋습니다.이 함수는 스페이스 패딩 문자열을 만드는 데 사용했지만 필요한 대로 템플릿을 변경할 수 있습니다.

function strRepeat(intLen, strTemplate) {
  strTemplate = strTemplate || "          ";
  var strTxt = '';
  while(intLen > strTemplate.length) {
    strTxt += strTemplate;
    intLen -= strTemplate.length;
  }
  return ((intLen > 0) ? strTxt + strTemplate.substr(0, intLen) : strTxt);
}

언급URL : https://stackoverflow.com/questions/14343844/create-a-string-of-variable-length-filled-with-a-repeated-character

반응형