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

  • برمجة سكالا

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.

الأجوبة

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
هل كان المحتوى مفيد؟

معلومات ذات صلة

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...