- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Replace Character in a String in Java without using replace() method
To replace a character in a String, without using the replace() method, try the below logic.
Let’s say the following is our string.
String str = "The Haunting of Hill House!";
To replace character at a position with another character, use the substring() method login. Here, we are replacing 7th position with character ‘p’
int pos = 7; char rep = 'p'; String res = str.substring(0, pos) + rep + str.substring(pos + 1);
The following is the complete example wherein a character at position 7 is replaced.
Example
public class Demo { public static void main(String[] args) { String str = "The Haunting of Hill House!"; System.out.println("String: "+str); // replacing character at position 7 int pos = 7; char rep = 'p'; String res = str.substring(0, pos) + rep + str.substring(pos + 1); System.out.println("String after replacing a character: "+res); } }
Output
String: The Haunting of Hill House! String after replacing a character: The Haupting of Hill House!
- Related Articles
- Java String replace() method example.
- How to use Java string replace method?
- Replace first occurrence of a character in Java
- Java Program to replace all occurrences of a given character in a string
- Replace a string using StringBuilder
- Replace String with another in java.
- String function to replace nth occurrence of a character in a string JavaScript
- Does JavaScript have a method to replace part of a string without creating a new string?
- Java Program to Replace the Spaces of a String with a Specific Character
- How to replace Digits into String using Java?
- C program to replace all occurrence of a character in a string
- C# Program to replace a special character from a String
- How to replace a character in Objective-C String for iPhone SDK?
- Java Program to Replace a Character at a Specific Index
- How to replace multiple spaces in a string using a single space using Java regex?

Advertisements