简体   繁体   中英

How to format a number such that first 6 digits and last 4 digits are not hidden

How to format a number such that first 6 digits and last 4 digits are not hidden

such that 111111111111111 looks like 111111****1111

One simple way to do this is to slit the input..

int number = 111111111111111;

string firstsix  =  number.ToString().Substring(0,6) //gets the first 6 digits
string middlefour = number.ToString().Substring(6,4) //gets the next 4
string rest = number.ToString().Substring(10, number.ToString().Lenght) //gets the rest

string combined = firstsix  + "****" +rest;

You can also use LINQ, substituting chars with indexes more than 5 and less than number.Length - 4 with * :

string number = "111111111111111";

string res = new string(number.Select((c, index) => { return (index <= 5 || index >= number.Length - 4) ? c : '*'; }).ToArray());

Console.WriteLine(res); // 111111*****1111

You need to use \\G anchor in-order to do a continuous string match.

string result = Regex.Replace(str, @"(?:^(.{6})|\G).(?=.{4})", "$1*");

DEMO

IDEONE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM