Scala Programming: Read a string and returns after remove a specified character and its immediate left and right characters
Write a Scala program to read a string and returns after remove a specified character and its immediate left and right characters.
Sample Solution:
Scala Code:
object Scala_String {
def test(str1: String, c: Char): String = {
var len = str1.length;
var resultString = "";
for (i <- 0 to len - 1) {
if (i == 0 && str1.charAt(i) != c)
resultString += str1.charAt(i);
if (i > 0 && str1.charAt(i) != c && str1.charAt(i - 1) != c)
resultString += str1.charAt(i);
if (i > 0 && str1.charAt(i) == c && str1.charAt(i - 1) != c)
resultString = resultString.substring(0, resultString.length() - 1);
}
return resultString;
}
def main(args: Array[String]): Unit = {
var str1 = "test#string";
var c = '#'
println("The given strings is: " + str1);
println("The new string is: " + test(str1, c));
str1 = "sdf$#gyhj#";
c = '$'
println("The given strings is: " + str1);
println("The new string is: " + test(str1, c));
}
}
Sample Output:
The given strings is: test#string The new string is: testring The given strings is: sdf$#gyhj# The new string is: sdgyhj#
Go to:
PREV : 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.
NEXT : Write a Scala program to check two given strings whether any one of them appear at the end of the other string (ignore case sensitivity).
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?