
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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!
Advertisements