Inverti una stringa in Javascript.

Apr 22 2023
I metodi String trattati in questo articolo saranno Split(), Reverse() e Join(). Le principali domande javascript saranno sulle stringhe durante un'intervista, quindi vogliamo assicurarci di imparare quegli hack sulle stringhe.

I metodi String trattati in questo articolo saranno Split() , Reverse() e Join() .

Le principali domande javascript saranno sulle stringhe durante un'intervista, quindi vogliamo assicurarci di imparare quegli hack sulle stringhe. Ti sei mai stupito che i metodi delle stringhe funzionino e soprattutto questo pezzo di codice .

const stringToReverse = "DonkeyBonkey";

const reversedString =stringToReverse.split("").reverse().join("");

console.log(reversedString);

// output = "yeknoByeknoD"

Metodo che tratteremo:

  1. diviso
  2. inversione
  3. giuntura

Il metodo split prende un modello della stringa e prende la sottostringa cercando il modello. In questo articolo non useremo nessuno dei metodi di stringa forniti da javascript, ma come scopriamolo. Il metodo Split accetta indent che significa stringhe vuote come argumentse passi "" this come una stringa vuota, divide tutti gli elementi nell'argomento che stai passando e restituisce come un array. Se lasci uno spazio vuoto nella stringa vuota come questa " ", il metodo split divide che sono tutti gli elementi ha un elemento stringa vuoto nel valore che stai passando e aggiunge i valori prima della stringa vuota e li inserisce nell'array come valore e va avanti. Se indent non è stato passato, unirà tutti gli elementi e restituirà un array a valore singolo.

const stringToBeSplitted = "Javascript string methods";

console.log(stringToBeSplitted.split("")); // ['J', 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', 'm', 'e', 't', 'h', 'o', 'd', 's']
console.log(stringToBeSplitted.split(" ")); // ['Javascript', 'string', 'methods']
console.log(stringToBeSplitted.split()); // ['Javascript string methods']

// split the string without using string methods.

class Strings {
  constructor(stringToReverse) {
    this.stringToReverse = stringToReverse;
    this.splittedString = [];
    this.indexedString = "";
  }

  Split(indent) {
    if (this.splittedString.length > 0) this.splittedString = [];  
    if (typeof this.stringToReverse !== 'string') return "Not a string data stype!";  
    if (indent === undefined) {
        this.splittedString = [this.stringToReverse];
        return this.splittedString;
    } else if (indent === "") {
      for (let i = 0; i < this.stringToReverse.length; i++) {
        this.splittedString.push(this.stringToReverse[i]);
      }
      return this.splittedString;
    } else {
      for (let i = 0; i < this.stringToReverse.length; i++) {
        if (this.stringToReverse[i].valueOf() !== " ") {
          this.indexedString += this.stringToReverse[i];
          if (i === this.stringToReverse.length - 1)
            this.splittedString.push(this.indexedString);
        } else {
          this.splittedString.push(this.indexedString);
          this.indexedString = "";
        }
      }
      return this.splittedString;
    }
  }
}

const strings = new Strings(stringToBeSplitted);
console.log(strings.Split("")); // ['J', 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', 'm', 'e', 't', 'h', 'o', 'd', 's']
console.log(strings.Split(" ")); // [ 'Javascript', 'string', 'methods' ]
console.log(strings.Split()); // [ 'Javascript string methods' ]

Il metodo inverso viene utilizzato per invertire l'array che prende un array come in argomento e scorre l'array e scambia l'elemento dall'indice sinistro a quello destro. Questo metodo è stato risolto utilizzando l'algoritmo Bubble sort .

const arrayToReverse = [1,2,3,4,5];

console.log(arrayToReverse.reverse()); // [5, 4, 3, 2, 1]

// reverse the array without using reverse() method.

class Strings {
  constructor() {
    this.splitIndent;
    this.reversedArray = [];
  }

  Reverse(array) {
    let iteratrionTimes = array.length;
    for (let i = 0; i < iteratrionTimes; i++) {
      let temp = array[i];
      this.reversedArray.push(
        array[array.length - 1]
      );
      array[array.length - 1] = temp;
      array.pop();
    }
    return this.reversedArray;
  }
}

const strings = new Strings();
console.log(strings.Reverse([1,2,3,4,5])); // [5, 4, 3, 2, 1]

Il metodo join prende l'array come argomento e li combina in una stringa e la restituisce. Prende un modello di matrice e scorre ogni elemento nell'array che utilizza Brute-Force Algorithm . Il rientro gioca un ruolo importante in questo metodo, la stringa che restituisce avrà il rientro dello spazio che abbiamo passato come argomento. Se il rientro non è stato passato, verrà convertito dal tipo di dati oggetto, ovvero dal tipo di dati definito dall'utente al tipo di dati stringa.

const arrayToJoin = [1,2,3,4,5];

console.log(arrayToJoin.join()); // '1,2,3,4,5'
console.log(arrayToJoin.join("")) // '12345'
console.log(arrayToJoin.join(" ")) // '1 2 3 4 5'


class Strings {
  Join(array, indent) {
    let joinedString = "";  
    let stringArr = String(array)
    if (indent === undefined) {
        return stringArr;
    } else if (indent === "") {
        for (let i = 0; i < stringArr.length; i++) {
            joinedString += i % 2 === 0 ? stringArr[i] : "";
        }
    } else {
        for (let i = 0; i < stringArr.length; i++) {
            joinedString += stringArr[i] === "," ? indent : stringArr[i]
        }
    }
     return joinedString
  }
}

const strings = new Strings();
console.log(strings.Join([1,2,3,4,5])); // '1,2,3,4,5'
console.log(strings.Join([1,2,3,4,5], "")); // '12345'
console.log(strings.Join([1,2,3,4,5], " ")); //'1 2 3 4 5'

Ecco il codice completo che stai cercando e anche questo codice può essere ottimizzato, ma l'ho lasciato libero ora perché per una migliore comprensione. Puoi copiare questo pezzo di codice eseguire questo codice per sapere come funziona .

const StringToReverse = "Donkey Bonkey";
console.log(StringToReverse.split("").reverse().join(""));

class Strings {
  constructor(stringToReverse) {
    this.splitIndent;
    this.stringToReverse = stringToReverse;
    this.splittedString = [];
    this.reversedArray = [];
    this.indexedString = "";
  }

  Split(indent) {
    this.splitIndent = indent;
    if (indent === "") {
      for (let i = 0; i < this.stringToReverse.length; i++) {
        this.splittedString.push(this.stringToReverse[i]);
      }
      return this;
    } else {
      for (let i = 0; i < this.stringToReverse.length; i++) {
        if (this.stringToReverse[i].valueOf() !== " ") {
          this.indexedString += this.stringToReverse[i];
          if (i === this.stringToReverse.length - 1)
            this.splittedString.push(this.indexedString);
        } else {
          this.splittedString.push(this.indexedString);
          this.indexedString = "";
        }
      }
      return this;
    }
  }

  Reverse() {
    let iteratrionTimes = this.splittedString.length;
    for (let i = 0; i < iteratrionTimes; i++) {
      let temp = this.splittedString[i];
      this.reversedArray.push(
        this.splittedString[this.splittedString.length - 1]
      );
      this.splittedString[this.splittedString.length - 1] = temp;
      this.splittedString.pop();
    }
    return this;
  }

  Join(indent) {
    let strArray = String(this.reversedArray);
    let reversedString = "";
    if (indent === undefined) return strArray
    else if (this.splitIndent === "") {
      for (let i = 0; i < strArray.length; i++) {
        reversedString += i % 2 === 0 ? strArray[i] : indent;
      }
    } else {
      for (let i = 0; i < strArray.length; i++) {
        reversedString += strArray[i] === "," ? indent : strArray[i];
      }
    }
    return reversedString;
  }
}

const strings = new Strings(StringToReverse);
console.log(strings.Split("").Reverse().Join(""));

Questo articolo si basa principalmente sul funzionamento dei metodi stringa. I metodi delle stringhe Javascript sono facili da usare e rendono il nostro codice più pulito e facile da capire, allo stesso tempo noi sviluppatori dobbiamo sapere come funzionano questi metodi. Grazie per aver letto questo articolo ♡.