![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Replace a Character at a Specific Index
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
Advertisements