Java String Exercises: New string with each character of just before and after of a non-empty substring whichever it appears in a non-empty given string
Java String: Exercise-85 with Solution
Write a Java program to make a new string with each character of just before and after of a non-empty substring whichever it appears in a non-empty given string.
Sample Solution:
Java Code:
import java.util.*;
public class Main
{
public String mAndTstring(String m_stng, String t_stng)
{
int m_st_len = m_stng.length();
int t_st_len = t_stng.length();
String fin = "";
for (int i = 0; i < m_st_len-t_st_len+1; i++)
{
String tmp = m_stng.substring(i,i+t_st_len);
if (i > 0 && tmp.equals(t_stng))
fin += m_stng.substring(i-1,i);
if (i < m_st_len-t_st_len && tmp.equals(t_stng))
fin += m_stng.substring(i+t_st_len,i+t_st_len+1);
}
return fin;
}
public static void main (String[] args)
{
Main m= new Main();
String str1 = "weablcoabmeab";
String str2 = "ab";
System.out.println("The given string are: "+str1+" and "+str2);
System.out.println("The new string is: "+m.mAndTstring(str1,str2));
}
}
Sample Output:
The given string are: weablcoabmeab and ab The new string is: elome
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to make a new string made of p number of characters from the first of a given string and followed by p-1 number characters till the p is greater than zero.
Next: Write a Java program to count the number of triples (characters appearing three times in a row) in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework