For example, if the function gets sent “4444444444444444” should return
“—————-**4444”
For example, if the function gets sent “4444444444444444” should return
“—————-**4444”
string.IsNullOrEmpty(string value)
Returns true if the string is null OR empty (“”).
It does not consider whitespace-only strings as empty.
string.IsNullOrWhiteSpace(string value)
Returns true if the string is null, empty, OR contains only whitespace (spaces, tabs, newlines).
Introduced in .NET 4.0.
Use IsNullOrWhiteSpace when validating user input, because users might accidentally enter only spaces.
Example: Credit card number, username, email, etc.
Use IsNullOrEmpty when checking strings in scenarios where whitespace might be considered valid.
Example: Some file paths, logs, or configurations.
public static string MaskCreditCard(string creditCardNumber){if (string.IsNullOrWhiteSpace(creditCardNumber))throw new ArgumentException("Credit card number cannot be null or empty.");creditCardNumber = creditCardNumber.Trim();if (creditCardNumber.Length <= 4)throw new ArgumentException("Credit card number must be more than 4 digits.");// Mask all but last 4 digitsstring lastFour = creditCardNumber.Substring(creditCardNumber.Length - 4);string masked = new string('*', creditCardNumber.Length - 4);return masked + lastFour;}
Here’s a C# function that accepts a credit card number and returns a string where all characters are replaced with asterisks except for the last four sprunki digits:
using System;
public class CreditCardHider
{
public static string HideCreditCardNumber(string creditCardNumber)
{
if (string.IsNullOrEmpty(creditCardNumber))
{
throw new ArgumentException(“Credit card number cannot be null or empty.”);
}
// Get the length of the credit card numberint length = creditCardNumber.Length;// Check if the number has at least 4 digitsif (length < 4){throw new ArgumentException("Credit card number must have at least 4 digits.");}// Create a string of asterisks for all but the last four charactersstring hiddenPart = new string('*', length - 4);string visiblePart = creditCardNumber.Substring(length - 4);// Combine and return the resultreturn hiddenPart + visiblePart;}public static void Main(string[] args){string creditCard = "1234567812345678";string hiddenCard = HideCreditCardNumber(creditCard);Console.WriteLine(hiddenCard); // Output: ************5678}
}