I've seen some interesting ways to handle strings with Linq:
For example, to hide numbers in a string by replacing them with X's I can do:
string strNum = "Hello, my number is ... 3456c456";
string strHidden = new String(strNum.ToCharArray()
.Select(c => (!char.IsNumber(c)) ? c : 'X').ToArray());
Console.WriteLine(strHidden);
Is there a Linq way to do this where numbers are replaced only if the current character is a number AND the following two characters are numbers?
There's a lot of ways to tailor the approach above, but I am wondering if there is an easy-ish linq way to do it with multiple characters at a time.
EDIT: added requirement for current character to be a number as well.
Based on the interpretation in my comment, you can do this with LINQ:
string strHidden = new String(Enumerable.Range(0, strNum.Length)
.Select(i =>
char.IsNumber(strNum[i]) &&
Enumerable.Range(i+1,2).All(j => j < strNum.Length && char.IsNumber(strNum[j]))
? 'X'
: strNum[i])
.ToArray());
Regular expression alternative:
var strHidden = Regex.Replace(strNum, @"\d(?=\d{2})", "X");
Much nicer, no?
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.