3

Using C#, what's the most efficient way to accomplish this?

string one = "(999) 999-9999"; string two = "2221239876"; // combine these into result result = "(222) 123-9876" 

String one will always have 9's.

I'm thinking some kind of foreach on string one and when it sees a 9, replace it with the next character in string two. Not quite sure where to go from there though...

4
  • Does the question mark mean that there may or may not be a digit in the first location. For Example 0123 with a mask of 9?9999 would result in 0123? Commented Feb 19, 2010 at 22:48
  • Do you just want to format a string of 10 numbers as a phone number? Because, there is an easier way to do that in c# Commented Feb 19, 2010 at 22:50
  • @Yuriy - Simplified the question by striking out the question mark. @Chris - Yes, I could use String.Format for a telephone number. But I'm wondering about any type of mask here. Sort of academic :) Commented Feb 19, 2010 at 22:52
  • 1
    You might want to put double-quotes around your second string literal too. Commented Feb 19, 2010 at 22:54

3 Answers 3

12

If you want to apply a certain format to a number, you can try this:

long number = 2221239876; string result = number.ToString("(###) ### ####"); // Result: (222) 123 9876 

For more information, see Custom Numeric Format Strings in the .NET Framework documentation.

Sign up to request clarification or add additional context in comments.

Comments

1
string one = "(999) 999-9999"; string two = "2221239876"; StringBuilder result = new StringBuilder(); int indexInTwo = 0; for (int i = 0; i < one.Length; i++) { char character = one[i]; if (char.IsDigit(character)) { if (indexInTwo < two.Length) { result.Append(two[indexInTwo]); indexInTwo++; } else { // ran out of characters in two // use default character or throw exception? } } else { result.Append(character); } } 

Comments

0

I am not quite sure how much you expect the pattern (the string 'one') to differ. If it will always look like you have shown it, maybe you could just replace the nines with '#' and use a .ToString(...).

Otherwise you may have to do something like

 string one = "(9?99) 999-9999"; string two = "2221239876"; StringBuilder sb = new StringBuilder(); int j = 0; for (int i = 0; i < one.Length; i++) { switch (one[i]) { case '9': sb.Append(two[j++]); break; case '?': /* Ignore */ break; default: sb.Append(one[i]); break; } } 

Obviously, you should check to make sure that no IndexOutOfRange exceptions will occur if either string is "longer" than the other (that is, 'one' contains more nines than the length of 'two' etc.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.