Astring is a sequence ofcharacters. Sometimes we need to access one character in the string. The Java String functioncharAt()
returns the character at a given position in a string, where positions start at0
.
Here is an example. First, we create a string in Java:
Strings="The quick brown fox jumped over the lazy dog.";
The string value is this entire sentence:The quick brown fox jumped over the lazy dog. The variables
refers to the string. We use this variable to invoke String methods on the string.
Next, we invoke thecharAt()
method on the string variables
, passing the parameter4
. This function returns thechar
value at position 4. Since string indexes start at0
, the function returns characterq
. Note that a space is a character too. The code assigns the return valueq
to thechar
variablec
:
charc=s.charAt(4);
Finally we outputc
:
System.out.println(c);// q
Here is a complete program:
publicclassExample{publicstaticvoidmain(String[]args){Strings="The quick brown fox jumped over the lazy dog.";charc=s.charAt(4);System.out.println(c);// q}}
Execute the program to see the outputq
in the terminal.
Note thats.charAt(0)
returns the first character in the string:T
.
Try thecharAt()
String function to retrieve other characters in the string.
Thanks for reading. 😃
Follow me on Twitter@realEdwinTorres
for more programming tips and help.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse