Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,562 questions

56,777 answers

573 users

How to mask a number with stars except the last 4 digits in Scala

3 Answers

0 votes
object Main {
    def maskNumber(value: Any, maskChar: Char = '*'): String = {
      val str = value.toString
      if (str.length <= 4) str
      else maskChar.toString * (str.length - 4) + str.takeRight(4)
    }

    def main(args: Array[String]) = {
        // Examples:
        println(maskNumber("1234567890123456")) // ************3456
        println(maskNumber(9876543210L))        // ******3210
        println(maskNumber("123"))               // 123
    }
}



/*
run:

************3456
******3210
123

*/


 



answered Oct 6 by avibootz
0 votes
object Main {
    def maskNumberPadTo(value: Any, maskChar: Char = '*'): String = {
      val str = value.toString
      if (str.length <= 4) str
      else str.takeRight(4).reverse.padTo(str.length, maskChar).reverse.mkString
    }

    def main(args: Array[String]) = {
        println(maskNumberPadTo("1234567890123456")) // ************3456
    }
}

        
        
/*
run:

************3456

*/


 



answered Oct 6 by avibootz
0 votes
object Main {
    def maskDigitsKeepFormat(value: Any, visibleDigits: Int = 4, maskChar: Char = '*'): String = {
      val str = value.toString
      val totalDigits = str.count(_.isDigit)
      
      if (totalDigits <= visibleDigits) str
      else {
        val digitsToMask = totalDigits - visibleDigits
        var maskedCount = 0
    
        str.map {
          case c if c.isDigit =>
            if (maskedCount < digitsToMask) {
              maskedCount += 1
              maskChar
            } else c
          case c => c
        }
      }
    }

    def main(args: Array[String]) = {
        println(maskDigitsKeepFormat("1234-5678-9012-3456")) // ****-****-****-3456
        println(maskDigitsKeepFormat("+1 (800) 555-0199"))    // +* (***) ***-0199
    }
}


                
/*
run:

****-****-****-3456
+* (***) ***-0199

*/

 



answered Oct 6 by avibootz
...