3
Reply

Write a function in CSharp that accepts a credit card number. It should returns a string where all the characters are hidden with an asterisk except the last four.

Md Masum Kazi

Md Masum Kazi

May 28
913
1
Reply

    1. public static string MaskCreditCard(string creditCardNumber)
    2. {
    3. if (string.IsNullOrWhiteSpace(creditCardNumber))
    4. throw new ArgumentException("Credit card number cannot be null or empty.");
    5. creditCardNumber = creditCardNumber.Trim();
    6. if (creditCardNumber.Length <= 4)
    7. throw new ArgumentException("Credit card number must be more than 4 digits.");
    8. // Mask all but last 4 digits
    9. string lastFour = creditCardNumber.Substring(creditCardNumber.Length - 4);
    10. string masked = new string('*', creditCardNumber.Length - 4);
    11. return masked + lastFour;
    12. }

    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.”);
    }

    1. // Get the length of the credit card number
    2. int length = creditCardNumber.Length;
    3. // Check if the number has at least 4 digits
    4. if (length < 4)
    5. {
    6. throw new ArgumentException("Credit card number must have at least 4 digits.");
    7. }
    8. // Create a string of asterisks for all but the last four characters
    9. string hiddenPart = new string('*', length - 4);
    10. string visiblePart = creditCardNumber.Substring(length - 4);
    11. // Combine and return the result
    12. return hiddenPart + visiblePart;
    13. }
    14. public static void Main(string[] args)
    15. {
    16. string creditCard = "1234567812345678";
    17. string hiddenCard = HideCreditCardNumber(creditCard);
    18. Console.WriteLine(hiddenCard); // Output: ************5678
    19. }

    }

    1. string.IsNullOrEmpty(string value)

    Returns true if the string is null OR empty (“”).

    It does not consider whitespace-only strings as empty.

    1. 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.