Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a "mask" to a string

I have a flag enumeration (int) mask, and I need to convert it to a string representing the day of a Week.

say this is the FULL string and an arbitrary mask

strFullWeek = "MTWtFSs"
strWeekMask = "0100110"
-----------------------
strResult   = "-T--FS-"

what way would you propose to obtains strResult from full week and mask strings?

UPDATE

this is my "entire context" (VB.NET)

<Flags()> Public Enum Week
  Monday = 1
  Tuesday = 2
  Wednesday = 4
  Thursday = 8
  Friday = 16
  Saturday = 32
  Sunday = 64
End Enum

Dim mondayOrSunday = Week.Monday Or Week.Sunday
Dim strDays = "MTWtFSs"

Dim strMondayOrSundayBinary = Convert.ToString(
  mondayOrSunday, 2).PadRight(7, CChar("0"))

Dim charMondayOrSunday = strDays.Zip(
  strMondayOrSundayBinary,
  Function(day, mask) If(mask = CChar("1"), day, CChar("-"))).ToArray()

Dim strMondayOrSunday = New String(charMondayOrSunday)

Console.WriteLine("{0} I see as {1}",
                  mondayOrSunday,
                  strMondayOrSunday)
like image 835
serhio Avatar asked Sep 21 '12 12:09

serhio


People also ask

How do you mask a string?

If you want to mask all characters with another character in one fell swoop you can use the String#replaceAll(String regex, String replacement) method: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String).

How do you mask numbers in C#?

In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input.


1 Answers

There's a reasonably neat LINQ way:

var chars = strFullWeek.Zip(strWeekMask, (day, mask) => mask == '1' ? day : '-'))
                       .ToArray();
string text = new string(chars);

It wouldn't be terribly efficient, but it may be good enough...

EDIT: Okay, assuming you're happy with C# code for the enum version

// TODO: Rename "Week" to comply with .NET naming conventions
Week mask = Week.Monday | Week.Sunday;
var chars = strFullWeek.Select((value, index) => (int) mask & (1 << index) != 0) 
                                                 ? value : '-')
                       .ToArray();
string text = new string(chars);
like image 122
Jon Skeet Avatar answered Sep 23 '22 17:09

Jon Skeet