w3resource

Scala Programming: Create a new string from a given string after removing the 2nd character from the substring of length three starting with 'z' and ending with 'g' presents in the said string

Scala Programming String Exercise-36 with Solution

Write a Scala program to create a new string from a given string after removing the 2nd character from the substring of length three starting with 'z' and ending with 'g' presents in the said string.

Sample Solution:

Scala Code:

object Scala_String {
  def test(stng: String): String = {
  val len = stng.length;
  var newformstring = "";
  for (i <- 0 to len-1) 
  {
    newformstring += stng.substring(i,i+1);
    if (i > 0 && i < len-1) 
	{
      if (stng.charAt(i-1) == 'z' && stng.charAt(i+1) == 'g')
        newformstring = newformstring.substring(0,newformstring.length()-1);
    }
  }
  newformstring;
  }
  def main(args: Array[String]): Unit = {
      var str1 =  "zzgkitandkatcaketoket";
      println("The given string is: "+str1);
      println("The new string is: "+test(str1));
      
      str1 =  "kitandkazzgtcaketoket";
      println("The given string is: "+str1);
      println("The new string is: "+test(str1));
    
      str1 =  "kitandkatcaketoketzzg";
      println("The given string is: "+str1);
      println("The new string is: "+test(str1));
  }
}

Sample Output:

The given string is: zzgkitandkatcaketoket
The new string is: zgkitandkatcaketoket
The given string is: kitandkazzgtcaketoket
The new string is: kitandkazgtcaketoket
The given string is: kitandkatcaketoketzzg
The new string is: kitandkatcaketoketzg

Scala Code Editor :

+

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to repeat a specific number of characters for specific number of times from the last part of a given string.
Next: Write a Scala program to check whether the character immediately before and after a specified character is same in a given string.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.