簡體   English   中英

如何在每個指定長度的字符后給字符串添加空格,並用一個空格填充其余字符?

[英]How can I add a space to a string after every specified length of chars and pad the remaining characters with one space?

我正在進行編碼挑戰,以加密字符串並在指定的字符長度后返回帶空格的加密字符串。 另外,剩下的剩余字符應使用額外的空格填充,以使其達到指定字符長度。 這是我嘗試做的:

const str =
  "If man was meant to stay on the ground, god would have given us roots.";

class SquareCode {
  constructor(text) {
    this.text = text;
  }

  // Remove spaces and punctuation
  normalizeString() {
    return this.text.replace(/[^\w]|_/g, "").toLowerCase();
  }

  // Get number of columns
  size() {
    return Math.ceil(Math.sqrt(this.normalizeString().length));
  }

  // Split string into chunks
  chunks() {
    const pattern = new RegExp(`.{1,${this.size()}}`, "g");
    return this.normalizeString().match(pattern);
  }

  // Encrypt String
  encryptString() {
    let code = "";
    const chunks = this.chunks();
    for (let i = 0; i < this.size(); ++i) {
    for (let j = 0; j < chunks.length; ++j) {
      code += chunks[j].slice(i, i + 1);

      const rowLength = this.size()-1;
      if (code.replace(/\s/g, '').length % rowLength === 0) code += ' ';
    }
  }
    return code;
  }
}

const work = new SquareCode(str);
console.log(work.encryptString());

這是我得到的輸出:“ imtgdvs恐懼者mayoogo anouuio ntnnlvt wttddes aohghns seoau”

這是預期的輸出:“ imtgdvs恐懼者mayoogo anouuio ntnnlvt wttddes aohghn ssauau”

這是提供更好環境的挑戰的鏈接挑戰

嘗試:

const str =
  "If man was meant to stay on the ground, god would have given us roots.";

class SquareCode {
  constructor(text) {
    this.text = text;
  }

  // Remove spaces and punctuation
  normalizeString() {
    return this.text.replace(/[^\w]|_/g, "").toLowerCase();
  }

  // Get number of columns
  size() {
    return Math.ceil(Math.sqrt(this.normalizeString().length));
  }

  // Split string into chunks
  chunks() {
    const pattern = new RegExp(`.{1,${this.size()}}`, "g");
    return this.normalizeString().match(pattern);
  }

  // Encrypt String
  encryptString() {
    let code = "";
    const chunks = this.chunks();
    const size = this.size();
    console.log(chunks);
    for (let i = 0; i < size; ++i) {
    for (let j = 0; j < chunks.length; ++j) {
      code += chunks[j].slice(i, i + 1);
    }
    code += ' '
  }
    return code;
  }
}

const work = new SquareCode(str);

console.log(work.encryptString());

當塊長度小於大小時,Slice返回一個空字符串,並在代碼中的每個“單詞”之后添加一個空格。 盡管在說明中的示例中,“ aohghn”后似乎有兩個空格,而不僅僅是一個空格,但是在您的問題中,對於所需的輸出,只有一個空格:

“ imtgdvs恐懼者mayoogo anouuio ntnnlvt wttddes aohghn ssauau”

“ imtgdvs恐懼者mayoogo anouuio ntnnlvt wttddes aohghn(2個空格)sseoau”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM