Scala Programming: Read a string and return the string without the first two characters
Scala Programming String Exercise-26 with Solution
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
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: 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.
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-26.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics