C # How to replace parts of one line with parts of another

Using C #, what is the most efficient way to do this?

string one = "(999) 999-9999";
string two = "2221239876";

// combine these into result

result = "(222) 123-9876"

The line will always have 9.

I think there is some kind of foreach on the first line, and when it sees 9, replace it with the next character in line two. Not quite sure where to go from there, though ...

+3
source share
3 answers

If you want to apply a specific number to a number, you can try the following:

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

For more information, see Custom Number Format Strings in the .NET Framework Documentation.

+12
source
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);
    }
}
+1
source

, , ( "" ) . , , , nines "#" .ToString(...).

, , -

        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 see if IndexOutOfRange exceptions occur if any row is โ€œlongerโ€ than the other (that is, โ€œoneโ€ contains more than nine than length โ€œtwoโ€, etc.)

0
source

Source: https://habr.com/ru/post/1733616/


All Articles