Issue
There are 3 text fields the user will type into
"To be inserted message" in first Text field
"The message" in second Text field
and a substring of the message in the third text field
The program should be able to insert "To be inserted message" in Message after the substring.
Example ↓
Message→ Stack flow
To be inserted message → over
substring→Stack
Output → Stack over flow
Solution
When do you want to insert substring into the main string you can use insert(int offset, A)
. But before you need to get the place where you need to put it and we need to REMEMBER that insert()
works with StringBuilder
. When you don't use it you can use method substring()
. From you example, as can be seen, you will point after substring. To do this, we need to find that substring into the main string whereby: indexOf(String str)
.
Assuming we have: mainSTR, subSTR and str after which we need to input subSTR.
String mainSTR = "Stack flow";
String subSTR = "over";
String str = "Stack";
Let's go to think!
int pos_str = mainSTR.indexOf(str)+str.length();
pos_str will point us for place. Also, for first input str we added its length. It needed to point the space after "Stack". Now we can input subSTR in mainSTR.
Here is an answer for you question: Insert a character in a string at a certain position
Using substring()
you need to take, at first, first part of main string, later add subSTR and later add second part of mainSTR.
Answered By - Vasyl Lyashkevych