Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Working with text
The String datatype has many useful methods we can use to get information from it.
Let's say we have a string, and we would like to get the 5th letter.
We can use charAt()
or []
notation.
Look at the code below:
Why did we use 4 to get the 5th letter and 9 to get the 10th letter?
Because the String index starts at 0. So ALPHABET.charAt(0)
is the first letter, ALPHABET.charAt(1)
is the second letter and so on.
The code above lets us find which letter is at a certain position in the String. What if we knew the letter, but wanted to find which position it's in, or what it's index is?
To do that we can use the indexOf()
method.
Note, indexOf()
returns the first occurance of the given string or character.
Look at the code below:
In the code below, create a variable called myChar
and set it to the character at 59th position of the string myString
.
Also create a variable called position
and set it equal to the position of the first occurance of the character j