c-sharp

Mask String

Mask string, mobile number etc. Usefull while logging sensitive content.

Abhith RajanSeptember 12, 2020 · 1 min read · Last Updated:
1/// <summary>
2/// Mask the string.
3/// </summary>
4/// <param name="value">String that need to be masked</param>
5/// <param name="startIndex">zero index indicating mask start position</param>
6/// <param name="mask">mask that need to be applied, eg. ***</param>
7/// <returns>Usage: "123456789".Mask(3, "****") => "123****89"</returns>
8public static string Mask(this string value, int startIndex, string mask)
9{
10 if (string.IsNullOrEmpty(value))
11 return string.Empty;
12
13 var result = value;
14 var starLength = mask.Length;
15
16 if (value.Length < startIndex) return result;
17
18 result = value.Insert(startIndex, mask);
19
20 result = result.Length >= (startIndex + (starLength * 2)) ? result.Remove(startIndex + starLength, starLength) : result.Remove(startIndex + starLength, result.Length - (startIndex + starLength));
21
22 return result;
23}

Tests

1"123456789".Mask(3, "****").Should().Be("123****89");
2"123456789".Mask(3, "****---").Should().Be("123****---");

Reference

Written by Abhith Rajan
Abhith Rajan is an aspiring software engineer with more than 8 years of experience and proven successful track record of delivering technology-based products and services.
Buy me a coffee

Was this helpful?

Show some ❤️

Share this page on Twitter to appear on the webmentions* 💡

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub

Related VideosView All

C# Channels Explained (System.Threading.Channels)

Semaphore Explained C#

Related StoriesView All