Getting a Character by Index From a String in Java

06 May 2023 Balmiki Mandal 0 Core Java

Getting a Character by Index From a String in Java

In Java, when working with strings, it's often necessary to extract character by index from a given string. Fortunately, Java provides a number of ways to accomplish this task. In this article, we'll discuss three different approaches.

Using the charAt() method

The most straightforward approach is to use the charAt() method. This method accepts an integer between 0 and the length of the string minus one and returns the character at that position. Here's an example:

String str = "Hello World";
char c = str.charAt(0);
System.out.println(c); // prints 'H'

As you can see, the character at index 0 is 'H'. The charAt() method works for both positive and negative indexes. A negative index indicates an offset from the end of the string, so the above example would still print 'H' if we used -11 as the argument.

Using the substring() method

Another way to get a character at a particular index is to use the substring() method. This method takes two arguments: the starting index and the ending index. It returns a new string containing the characters in the specified range. To get a single character, we simply need to provide the same index for both arguments. Here's an example:

String str = "Hello World";
String c = str.substring(0, 1);
System.out.println(c); // prints 'H'

Using the toCharArray() method

Finally, we can use the toCharArray() method to obtain an array of characters from a string. We can then use array notation to access the character at the desired index. Here's an example:

String str = "Hello World";
char[] chars = str.toCharArray();
char c = chars[0];
System.out.println(c); // prints 'H'

And that's all there is to it! As you can see, there are several different ways to get a character by index from a string in Java. Depending on your needs, one approach may be more convenient than another.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.