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.
distro
7242 gold badges11 silver badges26 bronze badges
-
2Of course it's possible. What have you tried so far? How would you approach the problem?distro– distro2022年07月16日 06:21:09 +00:00Commented Jul 16, 2022 at 6:21
-
You can use the String.indexOf(), make an array the do a while loop, you can search for the documentationMr. Innovator– Mr. Innovator2022年07月16日 06:23:44 +00:00Commented Jul 16, 2022 at 6:23
2 Answers 2
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)
answered Jul 16, 2022 at 6:23
Mohammad Ali Rony
4,9413 gold badges23 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Mohammad Ali Rony
if answered useful mark as answers
Chris P
If string start with ' ' (empty char) the first element of the array will be empty so do for the last char. So maybe a str.strip() (if there is in javascript may be used depends of the need).
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);
Comments
lang-js