In this article, we will understand how to get a character from the given string. Char is a datatype that contains an alphabets or an integer or an special character. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).
Below is a demonstration of the same −
Suppose our input is −
Input string: Java Programming Index: 11
The desired output would be −
Result: m
Algorithm
Step 1 - START Step 2 - Declare a string value namely input_string and a char value namely resultant_character. Step 3 - Define the values. Step 4 - Using the function string.charAt(), fetch the char value present at the specified position. Store the value in resultant_character. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class CharacterAndString {
public static void main(String[] args) {
String string = "Java Programming";
System.out.println("The string is defined as " +string);
int index = 11;
char resultant_character = string.charAt(index);
System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
}
}Output
The string is defined as Java Programming A character from the string :Java Programming at index 11 is: m
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class CharacterAndString {
public static char get_chararacter(String string, int index) {
return string.charAt(index);
}
public static void main(String[] args) {
String string = "Java Programming";
System.out.println("The string is defined as " +string);
int index = 11;
char resultant_character = get_chararacter(string, index);
System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
}
}Output
The string is defined as Java Programming A character from the string :Java Programming at index 11 is: m