课程: Learning Java 17
Using indexes with strings
- [Instructor] The student's first name and last name are separated into different strings. Instead of hard coding the initials, we can now calculate them. All we need to do is grab the first letter of the first name and the first letter of the last name to create each initial. Earlier, we talked about how the ordering of the letters within a string matters, and this is one place where that comes into play. For the string, Kayla, we say that K is at index or location zero. A is at index one, Y at index two, L at index three, and A at index four. This means to calculate the first initial of the first name, we'll want to access the character at index zero or the zeroth slot in the string. To do this, we can use a special string operator to access the letters inside first name. To grab the first character, we can use an operation called charAt. CharAt allows us to access a character at a specific location within a string. It takes one input, and that's the index or location of the character we want to access. Going back to the code, we can change the value of student first initial. We can have it be calculated from student first name. We'll use the charAt operation to access the zeroth character. That's our input, zero. Let's run it. And we get the same output. K for the student's first initial. Let's review what we just did. We referenced the first name string because that's the variable we want to access the character from. We wrote dot because the operation we want to use, charAt, is a string operation. We get this for free with the string data type. Then we write the name of the operation we want to use, charAt. Finally, we add our input, the index of the character we want to access, zero. The output of this operation is the character at index zero, and that's saved in the student first initial variable. Let's do the same for the last initial. We'll access student last name because that's the string we want to get the character from. We'll use charAt, and access the character at index zero, H. Let's run it again. And we get the same results. We just calculated data from another piece of data, a student's initials from the student's first and last name. We also learned that the concept of a data type consists not only of the different values it can store, but also the different operations we can use with it.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。