Scala Programming: Check whether a specified character is happy or not
Scala Programming String Exercise-44 with Solution
Write a Scala program to check whether a specified character is happy or not. A character is happy when the same character appears to its left or right in a string.
Sample Solution:
Scala Code:
object Scala_String {
def test(stng: String, spc: Char): Boolean = {
var l = stng.length();
var char_happy = true;
for (i <- 0 to l - 1) {
if (stng.charAt(i) == spc) {
if (i > 0 && stng.charAt(i - 1) == spc)
char_happy = true;
else if (i < l - 1 && stng.charAt(i + 1) == spc)
char_happy = true;
else
char_happy = false;
}
}
char_happy;
}
def main(args: Array[String]): Unit = {
var str1 = "azzlea";
var spc = 'z'
println("The given string is: " + str1);
println("Is " + spc + " happy in the said string: " + test(str1, spc));
str1 = "abcfdkefg";
spc = 'f'
println("The given string is: " + str1);
println("Is " + spc + " happy in the said string: " + test(str1, spc));
}
}
Sample Output:
The given string is: azzlea Is z happy in the said string: true The given string is: abcfdkefg Is f happy in the said string: false
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to count the number of triples (characters appearing three times in a row) in a given string.
Next: Write a Scala program to calculate the sum of the numbers appear in a given string.
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-44.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics