Scala Programming: Check whether a substring presents in the middle of another string
Scala Programming String Exercise-32 with Solution
Write a Scala program to check whether a given substring presents in the middle of another given string. Here middle means difference between the number of characters to the left and right of the given substring not more than 1.
Sample Solution:
Scala Code:
object Scala_String {
def test(str1: String, str2: String): Boolean = {
var l = str1.length
var mid_pos = l / 2;
if (l < 3)
false
if (l % 2 != 0) {
if (str2.equals(str1.substring(mid_pos - 1, mid_pos + 2))) {
true
} else {
false
}
} else if (str2.equals(str1.substring(mid_pos - 1, mid_pos + 2)) || str2
.equals(str1.substring(mid_pos - 2, mid_pos + 1))) {
true
} else
false
}
def main(args: Array[String]): Unit = {
val str2 ="abc"
var str1 ="wwabcwww";
println("The given string is: " + str1);
println("Is " + str2 + " appear in middle? " + test(str1, str2));
str1 ="wwwabcwww";
println("The given string is: " + str1);
println("Is " + str2 + " appear in middle? " + test(str1, str2));
str1 ="wwwwabcwww";
println("The given string is: " + str1);
println("Is " + str2 + " appear in middle? " + test(str1, str2));
str1 ="wwwwwabcwww";
println("The given string is: " + str1);
println("Is " + str2 + " appear in middle? " + test(str1, str2));
}
}
Sample Output:
The given string is: wwabcwww Is abc appear in middle? true The given string is: wwwabcwww Is abc appear in middle? true The given string is: wwwwabcwww Is abc appear in middle? true The given string is: wwwwwabcwww Is abc appear in middle? false
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to check whether a prefix string creates using the first specific characters in a given string appears somewhere else in the string.
Next: Write a Scala program to count how many times the substring 'life' present at anywhere in a given string. Counting can also happen for the substring 'li?e',any character instead of 'f'.
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