How to add characters to a string in C#

前端 未结 4 783
时光说笑
时光说笑 2021-01-21 03:13

Problem: I would like add characters to a phone.

So instead of displaying ###-###-####, I would like to display (###) ###-####.

I tried the foll

4条回答
  •  情歌与酒
    2021-01-21 03:40

    You can use a regular expression to extract the digit groups (regardless of - or () and then output in your desired format:

    var digitGroups = Regex.Matches(x, @"(\d{3})-?(\d{3})-?(\d{4})")[0].Groups.Cast().Skip(1).Select(g => g.Value).ToArray();
    
    var ans = $"({digitGroups[0]}) {digitGroups[1]}-{digitGroups[2]}";
    

提交回复
热议问题