In this article, we will understand how to replace a character at a specific index. 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: 6
The desired output would be −
Modified string: Java P%ogramming
Algorithm
Step 1 - START Step 2 - Declare a string value namely input_string , an integer namely index, a char value namely character, Step 3 - Define the values. Step 4 - Fetch the substring from index 0 to index value using substring(), concatenate with character specified, concatenate this with the substring from ‘index + 1’. Store the result. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class StringModify {
public static void main(String args[]) {
String input_string = "Java Programming";
int index = 6;
char character = '%';
System.out.println("The string is defined as: " + input_string);
input_string = input_string.substring(0, index) + character + input_string.substring(index + 1);
System.out.println("\nThe modified string is: " + input_string);
}
}Output
The string is defined as: Java Programming The modified string is: Java P%ogramming
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class StringModify {
static void swap(String input_string, int index, char character){
input_string = input_string.substring(0, index) + character + input_string.substring(index + 1);
System.out.println("\nThe modified string is: " + input_string);
}
public static void main(String args[]) {
String input_string = "Java Programming";
int index = 6;
char character = '%';
System.out.println("The string is defined as: " + input_string);
swap(input_string, index, character);
}
}Output
The string is defined as: Java Programming The modified string is: Java P%ogramming