array of char to string in c#

2020-05-08 07:21发布

I have a string that looks like a phone number. I'm using a lambda to extract an array of char. Then I want to convert this array into a string. This is what I have:

PhoneCandidate = "(123)-321-1234"; //this is just an example of what it could look like
var p = PhoneCandidate.Where(c => char.IsDigit(c)).ToArray();

string PhoneNumber = p.toString();

However, when I run this code, the variable PhoneNumber becomes just "System.Char[]" instead of the values inside the array.

What do I need to change?

Thanks.

标签: c#
7条回答
啃猪蹄的小仙女
2楼-- · 2020-05-08 07:39

Let's take this a whole new direction:

Dim digits as New Regex(@"\d");
string  phoneNumber = digits.Replace(PhoneCandidate, "");
查看更多
够拽才男人
3楼-- · 2020-05-08 07:41

Assuming p is a char[] you can use the following:

String phoneNumber = new String(p);
查看更多
Evening l夕情丶
4楼-- · 2020-05-08 07:47

You can use the string constructor that takes a char[].

string PhoneNumber = new string(p);
查看更多
Viruses.
5楼-- · 2020-05-08 07:51

probably the best bet is to use the string constructor per (@Adam Robinson) however as an alternative, you can also use string.Join(string separator,params string[] value) (MSDN docs here)

PhoneCandidate = "(123)-321-1234"; //this is just an example of what it could look like
var p = PhoneCandidate.Where(c => char.IsDigit(c)).ToArray();

string str = string.Join(string.Empty,p);
查看更多
Bombasti
6楼-- · 2020-05-08 07:57

Try with constructor res = new string(yourArray);

查看更多
干净又极端
7楼-- · 2020-05-08 07:57

One of the string constructors takes a char[]:

string PhoneNumber = new string(p);
查看更多
登录 后发表回答