Scala Programming: 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 Programming String Exercise-27 with Solution
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.
Sample Solution:
Scala Code:
object Scala_String {
def test(str1: String, c: Char): String = {
var temp = "";
for (i <- 0 to str1.length - 1) {
if (i == 0 && str1.charAt(i) != c)
temp += str1.charAt(i);
else if (i == 1 && str1.charAt(i) != c)
temp += str1.charAt(i);
else if (i > 1)
temp += str1.charAt(i);
}
return temp;
}
def main(args: Array[String]): Unit = {
var str1 = "aacyte";
var c = 'a'
println("The given strings is: " + str1 + ", specified character is: " + c);
println("The new string is: " + test(str1, c));
str1 = "bacyte";
c = 'a'
println("The given strings is: " + str1 + ", specified character is: " + c);
println("The new string is: " + test(str1, c));
str1 = "bbacyte";
c = 'a'
println("The given strings is: " + str1 + ", specified character is: " + c);
println("The new string is: " + test(str1, c));
}
}
Sample Output:
The given strings is: aacyte, specified character is: a The new string is: cyte The given strings is: bacyte, specified character is: a The new string is: bcyte The given strings is: bbacyte, specified character is: a The new string is: bbacyte
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 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'.
Next: Write a Scala program to read a string and returns after remove a specified character and its immediate left and right characters.
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-27.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics