最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternative to String Length Property - Stack Overflow

programmeradmin4浏览0评论

This is my first question to Stack Overflow as I start my programming journey so I wele any suggestions on improving my question asking or researching skills.

I'm trying to figure out how to determine the length of a string, without using .length. Instead, I'm allowed to utilise the string method called slice and the question asks that I take indices into account while I build a recursive code.

My approach is to think of this backwards by thinking of the easiest way to solve this without the aforementioned restriction first:

function stringLength (string) {
     return string.length;
}
  stringLength("Goodbye"); // This would invoke 7.

If I then utilise the .slice method and examine the indices:

"Goodbye".slice(0); // This would invoke "Goodbye".
"Goodbye".slice(7); // This would invoke "".

So to obtain the length of the string, I could also try to determine the number of characters I would have to 'slice' in order to invoke "" OR attempt to find the index of the final character in the string and add 1.

Below is my thinking thus far but not sure if I'm going in the right direction and I have no idea what should go in my else statement - any suggestions or advice?

function stringLength (string) {
    var index = 0; // I'm pretty sure this is wrong!

// My base case establishes that if the index number within the slice method invokes nothing, that index number is the length of the string

 if (string.slice(index) === "") {
   return index; 

// Otherwise, cycle through the function until the index number is correct. 

   } else {
       return string.slice(index + 1);
        }
}

This is my first question to Stack Overflow as I start my programming journey so I wele any suggestions on improving my question asking or researching skills.

I'm trying to figure out how to determine the length of a string, without using .length. Instead, I'm allowed to utilise the string method called slice and the question asks that I take indices into account while I build a recursive code.

My approach is to think of this backwards by thinking of the easiest way to solve this without the aforementioned restriction first:

function stringLength (string) {
     return string.length;
}
  stringLength("Goodbye"); // This would invoke 7.

If I then utilise the .slice method and examine the indices:

"Goodbye".slice(0); // This would invoke "Goodbye".
"Goodbye".slice(7); // This would invoke "".

So to obtain the length of the string, I could also try to determine the number of characters I would have to 'slice' in order to invoke "" OR attempt to find the index of the final character in the string and add 1.

Below is my thinking thus far but not sure if I'm going in the right direction and I have no idea what should go in my else statement - any suggestions or advice?

function stringLength (string) {
    var index = 0; // I'm pretty sure this is wrong!

// My base case establishes that if the index number within the slice method invokes nothing, that index number is the length of the string

 if (string.slice(index) === "") {
   return index; 

// Otherwise, cycle through the function until the index number is correct. 

   } else {
       return string.slice(index + 1);
        }
}
Share Improve this question asked Nov 21, 2016 at 6:34 misteryeomisteryeo 272 silver badges7 bronze badges 6
  • You can also loop the string and count each iteration. But can I ask why aren't you using .length property? – Mr_Green Commented Nov 21, 2016 at 6:37
  • .slice takes two arguments start and end but if you omit the second it considers it as the last index. Have a look w3schools./jsref/jsref_slice_string.asp And why are you not willing to use length property. – Manish Commented Nov 21, 2016 at 6:39
  • @Mr_Green it's part of the exercise while I'm doing this learning course. I'm personally familiar with the .length property but this exercise encourages us to think outside the box and utilise recursion. – misteryeo Commented Nov 21, 2016 at 6:48
  • @misteryeo By asking here you aren't thinking "out of the box" we are doing that.. – Mr_Green Commented Nov 21, 2016 at 6:55
  • @Mr_Green I'm only reaching out because I've already tried to explore different options and I'm stuck and having trouble figuring it out. I'm not looking for an answer so much as a finger in the right direction for me to continue to play around so I can learn. It's hard as a newbie! – misteryeo Commented Nov 21, 2016 at 7:00
 |  Show 1 more ment

8 Answers 8

Reset to default 3

There are several ways to find the length of a string without using .length on string

var str = "Goodbye";
console.log(str.split("").length); // I'm not using length on string, but on array

or

Using String.prototype.lastIndexOf(). It will returns the index within the calling String object of the last occurrence of the specified value, searching from backwards.

var str = "Goodbye";
console.log(str.lastIndexOf(""));

or

var str = "Goodbye";

var length = 0;
while (str != "") {
  str = str.substring(1);
  ++length;
}

console.log(length);

Since you are supposed to use the slice method:

function stringLength(s) {
    let i = 0; 
    while(s != '') { 
        i += 1; 
        s = s.slice(1); 
    } 
    return i;
}

here is a recursive solution using slice:

var s = "Goodbye";

console.log(stringLength(s));

function stringLength (string, length) {
  length = length || 0;
  if (string.slice(length)) {
    return stringLength(string, ++length);
  }
  return length;
}

Read the documentation for slice. It returns a new string which is a portion of the old string. That means you can repeatedly slice one character off the string until you have nothing left. Count the number of slices you made and you know how long the string is!

Sample code

function stringLengthBySlice(s) {
    var length = 0;
    while(s != "") {
        s = s.slice(1);    // This is the key line.  It takes a slice of the string with 
                           // all but the first character.
        length++'
    }

    return length;
}

You can use bination of Array.forEach and split()

function stringLength(str) {
  var myArray = str.split('');
  var i = 0;
  myArray.forEach(function(value) {
    i++;
  });
  return i;
}

console.log(stringLength("Goodbye"))

what about this:

var count = 0, string = "Goodbye";
string.split('').forEach(function(){
    count++;
});
console.log(count);

Simply try this forEach().Its start from 0

var length=0;
var testing = "Goodbye".split("").forEach(function (item,index){
    length =index;
})

console.log(length)//0 to 6 

You can use the lastIndexOf string property.

The index of the first character is 0, and the index of the last character is str.length - 1. The lastIndexOf() method is case sensitive

'Goodbye'.lastIndexOf('')
发布评论

评论列表(0)

  1. 暂无评论