Scala Programming: Read a string, 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.
Sample Solution:
Scala Code:
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
Go to:
PREV : Write a Scala program to check whether the first two characters present at the end of a given string.
NEXT : Write a Scala program to read a string and return the string without the first two characters. Keep the first char if it is 'g' and keep the second char if it is 'h'.
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?