Skip to content

Sampe code for Uniform case string check #1427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.baeldung.scala.uniformcase

object UniformCaseChecker {

def convertAndCheck(str: String): Boolean = {
str.toUpperCase == str || str.toLowerCase == str
}

def isUpperLowerAndForAll(str: String): Boolean = {
val filteredStr = str.filter(_.isLetter)
filteredStr.forall(_.isUpper) || filteredStr.forall(_.isLower)
}

def regexCheck(str: String): Boolean = {
val filteredStr = str.filter(_.isLetter)
filteredStr.matches("^[A-Z]*$") || filteredStr.matches("^[a-z]*$")
}

def countAndCheck(str: String): Boolean = {
val filteredStr = str.filter(_.isLetter)
filteredStr.count(_.isUpper) == 0 || filteredStr.count(_.isLower) == 0
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.baeldung.scala.uniformcase

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.prop.TableDrivenPropertyChecks
import UniformCaseChecker.*

class UniformCaseCheckerUnitTest
extends AnyFlatSpec
with Matchers
with TableDrivenPropertyChecks {

private val fns =
Seq(convertAndCheck, isUpperLowerAndForAll, regexCheck, countAndCheck)

private val table = Table(
("Input", "Expected Result"),
("BAELDUNG @ 2024", true),
("baeldung @ 2024", true),
("Baeldung @ 2024", false),
("2024 @@@ ", true),
(" ", true)
)

it should "check if all characters are upper or lower" in {
fns foreach { fn =>
forAll(table) { (input, expected) =>
withClue("for string: " + input) {
fn(input) shouldBe expected
}
}
}
}
}