1

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.

3
  • 1
    Unrelated, but you could change your Where to a method group: PhoneCandidate.Where(char.IsDigit).ToArray() Commented Dec 18, 2011 at 20:19
  • does this change make it any faster to run? Commented Dec 18, 2011 at 20:33
  • Nope, gets compiled to the same thing. Commented Dec 18, 2011 at 22:09

7 Answers 7

6

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

string PhoneNumber = new string(p);
Sign up to request clarification or add additional context in comments.

3 Comments

Would this execute faster or not? string PhoneNumber = new string(PhoneCandidate.Where(c => char.IsDigit(c)).ToArray());
@frenchie: That will compile to identical IL.
Ok, thanks for this clarification. Probably better to leave it as for future clarity then.
3
string phone = new string(p);

Comments

2

Try with constructor res = new string(yourArray);

Comments

2

One of the string constructors takes a char[]:

string PhoneNumber = new string(p);

Comments

1

Let's take this a whole new direction:

Dim digits as New Regex(@"\d");
string  phoneNumber = digits.Replace(PhoneCandidate, "");

2 Comments

Which do you think is faster? A regex or a linq expression?
@frenchie You should measure based on real data and volume, but I would expect the Regex to do a lot better here.
0

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

String phoneNumber = new String(p);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.