Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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#

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now