Q:

Write a Scala program to read a given string and if the first or last characters are same return the string without those characters otherwise return the string unchanged

0

Write a Scala program to read a given string and if the first or last characters are same return the string 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_str = str1
    if (temp_str.length == 0)
      return temp_str;
    if (temp_str.length == 1) {
      if (temp_str.charAt(0) == c)
        return "";
      else
        return temp_str;
    }
    if (str1.charAt(0) == c)
      temp_str = temp_str.substring(1, temp_str.length);
    if (str1.charAt(str1.length - 1) == c)
      temp_str = temp_str.substring(0, temp_str.length - 1);
    return temp_str;
  }

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

    str1 = "testcricket";
    c = 'e'
    println("The given strings is: " + str1);
    println("The new string is: " + test(str1, c));
  }
}

Sample Output:

The given strings is: testcricket
The new string is: estcricke
The given strings is: testcricket
The new string is: testcricket

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