如何在C#中向字符串添加字符 [英] How to add characters to a string in C#
问题描述
问题:我想在手机中添加字符.
因此,我不想显示(###)###-####.#p ####################################################################################################
我尝试了以下操作:
string x ="Phone_Number";字符串y = x.Remove(0,2);//删除"1-"
从这里开始,我不确定如何在###
周围添加()"任何帮助将不胜感激.
值得注意的是,字符串在C#中是不可变的.这意味着,如果您尝试修改一个字符串,则始终会得到一个新的字符串对象.
一种方法是将其转换为数字(作为健全性检查),然后格式化字符串
var结果= String.Format("{0:(###)###-####}",double.Parse("8005551234"))
如果您不想进行双重转换,则可以执行以下操作:
var结果= String.Format(({{}} {1}-{2}"),x.Substring(0,3),x.Substring(3,3),x.Substring(6));
或者,如果您已经有连字符并且真的只想插入括号,那么您可以执行以下操作:
var结果= x.Insert(3,)").Insert(0,(");
Problem: I would like add characters to a phone.
So instead of displaying ###-###-####, I would like to display (###) ###-####.
I tried the following:
string x = "Phone_Number";
string y = x.Remove(0,2);//removes the "1-"
From here, I am not sure how I would add "()" around ###
Any help would be appreciated.
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, "(");
这篇关于如何在C#中向字符串添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!