Amrit Pant
Amrit Pant

Reputation: 11

How to split a string into array without using Array.split?

Is it possible to implement Array.split() just by using loops without using any built in functions?

I want this: "Hello how are you" ---> ["Hello" , "how", "are", "you"] without using Array.split() or any built in function.

Upvotes: 1

Views: 105

Answers (2)

murat-es
murat-es

Reputation: 1

let word = "stack over flow murat";
let arr = []
let tempWord= ""

for (let i = 0; i<word.length; i++){
if(word[i]===" "){
    arr.push(tempWord);
    tempWord="";
}
else{
    tempWord+=word[i];
    }
}
arr.push(tempWord);
console.log(arr);

Upvotes: 0

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4925

try this

let str= "Hello how are you";
 
let array = [''];
let j = 0;

for (let i = 0; i < str.length; i++) {
    if (str.charAt(i) == " ") {
        j++;
        array.push('');
    } else {
        array[j] += str.charAt(i);
    }
}
console.log(array)

Upvotes: 2

Related Questions