Scala Programming: Read a string, if the first or last characters are same return the string without those characters otherwise return the string unchanged
Scala Programming String Exercise-25 with Solution
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
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: 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'.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/string/scala-string-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics