Scala Programming: New string with each character of just before and after of a non-empty substring whichever it appears in a non-empty given string
Write a Scala 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:
Scala Code:
object Scala_String {
def test(m_stng: String, t_stng: String): String = {
var m_st_len = m_stng.length();
var t_st_len = t_stng.length();
var fin = "";
for (i <- 0 to m_st_len-t_st_len)
{
var 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);
}
fin;
}
def main(args: Array[String]): Unit = {
val str1 = "weablcoabmeab";
val str2 = "ab";
println("The given string are: "+str1+" and "+str2);
println("The new string is: "+test(str1, str2));
}
}
Sample Output:
The given string are: weablcoabmeab and ab The new string is: elome
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala 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 Scala 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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics