C# How to replace parts of one string with parts of another
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 so开发者_Go百科me 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...
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.
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);
}
}
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.)
精彩评论