I want to exchange all occurences of a character in a string with their case-counterpart.
For example:
"%Y %m %d | %H:%M:%S"
should become
"%Y %M %d | %H:%m:%S"
for the character 'm' or 'M'.
How can I best do this in C# ?
I want to exchange all occurences of a character in a string with their case-counterpart.
For example:
"%Y %m %d | %H:%M:%S"
should become
"%Y %M %d | %H:%m:%S"
for the character 'm' or 'M'.
How can I best do this in C# ?
You could use regexes... there are two possibilities here:
One using two distinct groupings and choosing which grouping was used in the replace function:
var rx1 = new Regex("(%M)|(%m)");
string original1 = "%Y %m %d | %H:%M:%S";
string modified1 = rx1.Replace(original1, x => x.Groups[1].Success ? "%m" : "%M");
The other simply taking a look in the replace function on what is the matched text.
var rx2 = new Regex("%[Mm]");
string original2 = "%Y %m %d | %H:%M:%S";
string modified2 = rx2.Replace(original2, x => x.Value == "%M" ? "%m" : "%M");
Just as a curiousity, I'll add two regexes that handle the escaping of a %
with another %
: %m
is month, %%m
is the string %m
, %%%m
is %
plus the month.
var rx1 = new Regex("(?<=(?:^|[^%])(?:%%)*)(?:(%M)|(%m))");
and
var rx2 = new Regex("(?<=(?:^|[^%])(?:%%)*)%[Mm]");
For ASCII letters, the 6ᵗʰ bit can be used to switch between upper and lower case:
var s = "%Y %m %d | %H:%M:%S";
s = string.Concat(s.Select(c => (c | 32) == 'm' ? (char)(c ^ 32) : c));