Scala Programming: Read a string and return the string without the first two characters
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'.
Sample Solution:
Scala Code:
object Scala_String {
def test(str1: String): String = {
var len = str1.length;
var temp = "";
for (i <- 0 to len - 1) {
if (i == 0 && str1.charAt(i) == 'g')
temp += 'g';
else if (i == 1 && str1.charAt(i) == 'h')
temp += 'h';
else if (i > 1)
temp += str1.charAt(i);
}
return temp;
}
def main(args: Array[String]): Unit = {
var str1 = "ghost";
println("The given strings is: " + str1);
println("The new string is: " + test(str1))
str1 = "photo";
println("The given strings is: " + str1);
println("The new string is: " + test(str1))
str1 = "goat";
println("The given strings is: " + str1);
println("The new string is: " + test(str1))
}
}
Sample Output:
The given strings is: ghost The new string is: ghost The given strings is: photo The new string is: hoto The given strings is: goat The new string is: gat
Go to:
PREV : 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.
NEXT : 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.
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?