![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
Insert a String into another String in Java
Let’s say we have a string “That’s good!” and within that we need to insert the text “no”. Therefore, the resultant string should be “That’s no good!” −
String str = "That's good!"; String newSub = "no ";
Now, the index where the new sub string will get inserted −
int index = 6;
Insert the new substring now −
StringBuffer resString = new StringBuffer(str); resString.insert(index + 1, newSub);
Let us now see an example to insert a string into another −
Example
import java.lang.*; public class Main { public static void main(String[] args) { String str = "That's good!"; String newSub = "no "; int index = 6; System.out.println("Initial String = " + str); System.out.println("Index where new string will be inserted = " + index); StringBuffer resString = new StringBuffer(str); resString.insert(index + 1, newSub); System.out.println("Resultant String = "+resString.toString()); } }
Output
Initial String = That's good! Index where new string will be inserted = 6 Resultant String = That's no good!
Advertisements