How to add characters to a string in C#

前端 未结 4 785
时光说笑
时光说笑 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:22

    It's worth noting that strings are immutable in C#.. meaning that if you attempt to modify one you'll always be given a new string object.

    One route would be to convert to a number (as a sanity check) then format the string

    var result = String.Format("{0:(###) ###-####}", double.Parse("8005551234"))
    

    If you'd rather not do the double-conversion then you could do something like this:

    var result = String.Format("({0}) {1}-{2}", x.Substring(0 , 3), x.Substring(3, 3), x.Substring(6));
    

    Or, if you already have the hyphen in place and really just want to jam in the parenthesis then you can do something like this:

    var result = x.Insert(3, ")").Insert(0, "(");
    

提交回复
热议问题