w3resource

Scala Programming: Check whether the character immediately before and after a specified character is same in a given string

Scala Programming String Exercise-37 with Solution

Write a Scala program to check whether the character immediately before and after a specified character is same in a given string.

Sample Solution:

Scala Code:

object Scala_String {
  def test(stng: String, schar: Char): Boolean = {
    var l = stng.length;
    var found = true;
    var tmpString: Char = ' '
    for (i <- 0 to l - 1) {
      tmpString = stng(i)
      if (tmpString.compare(schar) == 0) {
        if (stng.charAt(i - 1) == stng.charAt(i + 1)) {
          found = true;
        } else {
          found = false;

        }
      }
    }
    found;
  }
  
  def main(args: Array[String]): Unit = {
    var str1 = "moon#night";
    var schar: Char = '#'
    println("The given string is: " + str1 + " and the specified character is: " + schar);
    println("The before and after " + schar + " both characters are same in the said string: " + test(str1,schar));
    str1 = " bat#$#ball"
    schar = '$'
    println("The given string is: " + str1 + " and the specified character is: " + schar);
    println("The before and after " + schar + " both characters are same in the said string: " + test(str1,schar))
    str1 = " bat#$ball"
    schar = '$'
    println("The given string is: " + str1 + " and the specified character is: " + schar);
    println("The before and after " + schar + " both characters are same in the said string: " + test(str1,schar))
  }
 }

Sample Output:

The given string is: moon#night and the specified character is: #
The before and after # both characters are same in the said string: true
The given string is:  bat#$#ball and the specified character is: $
The before and after $ both characters are same in the said string: true
The given string is:  bat#$ball and the specified character is: $
The before and after $ both characters are same 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 create a new string from a given string after removing the 2nd character from the substring of length three starting with 'z' and ending with 'g' presents in the said string.
Next: Write a Java program to check whether two strings of length 3 and 4 appear in same number of times in a given string.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/scala-exercises/string/scala-string-exercise-37.php