Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Edwin Torres
Edwin Torres

Posted on • Edited on

     

How-To: Java charAt() String Function

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.";
Enter fullscreen modeExit fullscreen mode

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);
Enter fullscreen modeExit fullscreen mode

Finally we outputc:

System.out.println(c);// q
Enter fullscreen modeExit fullscreen mode

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}}
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Department Chief Engineer @MITREcorp. CS professor @monmouthu. Proud husband and father ❤️. My tweets are my own.
  • Location
    NJ
  • Education
    Doctor of Engineering, George Washington University
  • Work
    Principal Software Engineer at MITRE
  • Joined

More fromEdwin Torres

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp