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?
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)
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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With