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?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework