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'
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'.
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
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer