Skip to content
Fix Code Error

Get string character by index – Java

March 13, 2021 by Code Error
Posted By: Anonymous

I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the nth position? So in the string “foo”, if I asked for the character with index 0 it would return “f”.

Note – in the above question, by “character” I don’t mean the char data type, but a letter or number in a string. The important thing here is that I don’t receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.

Solution

The method you’re looking for is charAt. Here’s an example:

String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f

For more information, see the Java documentation on String.charAt. If you want another simple tutorial, this one or this one.

If you don’t want the result as a char data type, but rather as a string, you would use the Character.toString method:

String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f

If you want more information on the Character class and the toString method, I pulled my info from the documentation on Character.toString.

Answered By: Anonymous

Related Articles

  • How can I resolve Web Component Testing error?
  • Is CSS Turing complete?
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Unable to run Robolectric and Espresso with a…
  • When I'm testing a web app by JUnit and Mockito I get many…
  • ClassNotFoundException:…
  • Eclipse will not start and I haven't changed anything
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Neither BindingResult nor plain target object for bean name…
  • Jetpack Compose and Hilt Conflict

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Pass a string parameter in an onclick function

Next Post:

Make body have 100% of the browser height

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error