1

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
asked Jul 16, 2022 at 6:18
2
  • 2
    Of course it's possible. What have you tried so far? How would you approach the problem? Commented 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 documentation Commented Jul 16, 2022 at 6:23

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

if answered useful mark as answers
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).
0
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);
answered Jul 16, 2022 at 14:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.