- Trending Categories
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!
- Related Articles
- Java Program to Insert a string into another string
- Golang program to insert a string into another string
- How to insert a string in beginning of another string in java?
- String Transforms Into Another String in Python
- Java program to insert a String into a Substring of StringBuffer
- How to copy a String into another String in C#
- Replace String with another in java.
- How do I determine if a String contains another String in Java?
- Print all possible ways to convert one string into another string in C++
- Convert Short into String in Java
- Place Stack Trace into a String in Java
- Replace one string with another string with Java Regular Expressions
- How to check if a String contains another String in a case insensitive manner in Java?
- Split a string and insert it as individual values into a MySQL table?
- How to convert a String into int in Java?

Advertisements