Lesson 3 Practice 1

Why are we taking (0,3) and not (0,2) [for the first name and last name, firstName.substring(0,3).ToUpper] to generate the nickname since we want the first three characters only?

Because the second parameter is the length of the substring, so the amount of characters you want to extract. It starts the substring at index 0, then gets 3 characters, so index 2 is the last character it will include in the substing (index 0, 1 and 2). :slight_smile:

So as the array starts from index 0, index 0, index 1 and index 2 will take the first 3 letters of the first name and last name but then what’s the role of index 3 in this?

3 here is not the index, but the length you want to sub-string.


substring(0 :point_left: start here, 3 :point_left: take these number of char)

hope it helps

@Tanyak, the 3 is not an index, it is merely the amount of characters. The confusing bit is that it starts at index 0, but lets say you would want to extract the substring ‘wor’ from ‘hello world’. In this case you would type variable.substring(6, 3). Here ‘w’ is at index 6, which is the start index. You want to extract 3 characters, so the second parameter of the substring method is 3. It doesn’t clarify the endpoint index, it only states how long the substring should be.

Does that make it more clear?

newString = oldString.Substring(int1,int2)

here ‘int1’ would be the index of character you want the substring to start and ‘int2’ is total length of new string or substring.

I believe you get my point now.

Thank you all. I got it. :slight_smile:

1 Like