jeramay10
jeramay10

Reputation: 155

ASP.Net - Masked first 6 character on a string with dynamic length

is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?

Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.

Upvotes: 1

Views: 525

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186748

Linq is an alternative to Substring and ternary operator solution (see Zohar Peled's answer):

using System.Linq;

...

string original = "Some string here"; 
string result = "******" + string.Concat(original.Skip(6));

If you want to preserve the length of short (less than 6 character string):

// if original shorter than 6 symbols, e.g. "short" 
// we'll get "*****" (Length number of *, not 6)
// if original has six or more symbols, e.g. "QuiteLong" 
// we'll get "******ong" as usual 
string original = "short"; 
...
string result = new string('*', Math.Min(6, original.Length)) + 
                string.Concat(original.Skip(Math.Min(6, original.Length)));

You may want to have the routine as an extension method:

public static partial class StringExtensions {
  public static string MaskPrefix(this string value, int count = 6) {
    if (null == value)
      throw new ArgumentNullException("value"); // or return value
    else if (count < 0)
      throw new ArgumentOutOfRangeException("count"); // or return value

    int length = Math.Min(value.Length, count);

    return new string('*', length) + string.Concat(value.Skip(length));
  }
}

And so you can put as if string has MaskPrefix method:

string original = "Some string here";
string result = original.MaskPrefix(6);

Upvotes: 2

Zohar Peled
Zohar Peled

Reputation: 82484

Yes, it's possible, and even quite easy, using simple string concatenation and SubString:

var original = "Some string here";
var target = "******" + ((original.Length > 6) ? original.Substring(6) : "") ;

If you want shorter strings to mask all characters but keep original length, you can do it like this:

var target = new string('*', Math.Min(original.Length, 6)) + ((original.Length > 6) ? original.Substring(6) : "") ;

This way, an input of "123" would return 3 asterisks ("***"). The first code I've shown will return 6 asterisks ("******")

Upvotes: 2

i3lai3la
i3lai3la

Reputation: 980

You can substring and mask it. Make sure to check if the input string is lower than 6 as below sample

    string str = "123456789345798";
    var strResult = "******"+str.Substring(6, str.Length - 6);
    Console.WriteLine("strResult :" + strResult);

Upvotes: 0

Related Questions