Java - Getting a character by index from a string

By IncludeHelp Last updated : January 29, 2024

Problem statement

Given a string, you have to find a character by index using Java program.

Getting a character by index from a string

For this purpose, you can use the String.charAt() method which is a library method of String class, it is used to get/retrieve the specific character from a string. Where, the index starts from 0 and ends to String.lenght-1.

For example, if there is string "Hello", its index will starts from 0 and end to 4.

Exception while getting a character by index

If you try to access the character out of bounds, an exception StringIndexOutOfBoundsException will generate. So, be careful while using index in the string.

Java getting character by index: Example 1

In this example, there is string initialized by "Hello world!" and we have to access its 0th and 7th character.

public class Main {
  public static void main(String[] args) throws java.lang.Exception {
    String msg = "Hello world!";

    System.out.println("Character at 0th index: " + msg.charAt(0));
    System.out.println("Character at 7th index: " + msg.charAt(7));
  }
}

Output

Character at 0th index: H
Character at 7th index: o

Java getting character by index: Example 2

In this example, we have to read a string and print it character by character

import java.util.*;

public class Main {
  public static void main(String[] args) throws java.lang.Exception {
    //string Object
    String msg = null;

    //Scanner class Object
    Scanner scan = new Scanner(System.in);

    //input a string
    System.out.println("Input a string: ");
    msg = scan.nextLine();

    //printing string character by character
    System.out.println("Input string is: ");
    for (int loop = 0; loop < msg.length(); loop++)
      System.out.print(msg.charAt(loop));
  }
}

Output

Input a string:  I love programming.
Input string is: 
I love programming.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.