w3resource

Scala Programming: Read a string and returns after remove a specified character and its immediate left and right characters

Scala Programming String Exercise-28 with Solution

Write a Scala program to read a string and returns after remove a specified character and its immediate left and right characters.

Sample Solution:

Scala Code:

object Scala_String {
  def test(str1: String, c: Char): String = {
    var len = str1.length;
    var resultString = "";
    for (i <- 0 to len - 1) {
      if (i == 0 && str1.charAt(i) != c)
        resultString += str1.charAt(i);
      if (i > 0 && str1.charAt(i) != c && str1.charAt(i - 1) != c)
        resultString += str1.charAt(i);
      if (i > 0 && str1.charAt(i) == c && str1.charAt(i - 1) != c)
        resultString = resultString.substring(0, resultString.length() - 1);
    }
    return resultString;
  }
  def main(args: Array[String]): Unit = {
    var str1 = "test#string";
    var c = '#'
    println("The given strings is: " + str1);
    println("The new string is: " + test(str1, c));
    str1 = "sdf$#gyhj#";
    c = '$'
    println("The given strings is: " + str1);
    println("The new string is: " + test(str1, c));
  }
}

Sample Output:

The given strings is: test#string
The new string is: testring
The given strings is: sdf$#gyhj#
The new string is: sdgyhj#

Scala Code Editor :

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

Previous: Write a Scala program to read a string and if one or both of the first two characters is equal to specified character return without those characters otherwise return the string unchanged.
Next: Write a Scala program to check two given strings whether any one of them appear at the end of the other string (ignore case sensitivity).

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/string/scala-string-exercise-28.php