views:

288

answers:

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...

+12  A: 

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.

Anders Fjeldstad
A: 

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

Rune
+1  A: 
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);
    }
}
Zach Johnson