Create a string of variable length, filled with a repeated character

前端 未结 10 1103
刺人心
刺人心 2020-11-28 03:59

So, my question has been asked by someone else in it\'s Java form here: Java - Create a new String instance with specified length and filled with specific character. Best so

10条回答
  •  庸人自扰
    2020-11-28 04:37

    Based on answers from Hogan and Zero Trick Pony. I think this should be both fast and flexible enough to handle well most use cases:

    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)  
        }  
    }  
    

提交回复
热议问题