Q:

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

0

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

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 temp = "";
    for (i <- 0 to str1.length - 1) {
      if (i == 0 && str1.charAt(i) != c)
        temp += str1.charAt(i);
      else if (i == 1 && str1.charAt(i) != c)
        temp += str1.charAt(i);
      else if (i > 1)
        temp += str1.charAt(i);
    }
    return temp;
  }

  def main(args: Array[String]): Unit = {
    var str1 = "aacyte";
    var c = 'a'
    println("The given strings is: " + str1 + ", specified character is: " + c);
    println("The new string is: " + test(str1, c));

    str1 = "bacyte";
    c = 'a'
    println("The given strings is: " + str1 + ", specified character is: " + c);
    println("The new string is: " + test(str1, c));

    str1 = "bbacyte";
    c = 'a'
    println("The given strings is: " + str1 + ", specified character is: " + c);
    println("The new string is: " + test(str1, c));
  }
}

Sample Output:

The given strings is: aacyte, specified character is: a
The new string is: cyte
The given strings is: bacyte, specified character is: a
The new string is: bcyte
The given strings is: bbacyte, specified character is: a
The new string is: bbacyte

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