[英]C# How to replace parts of one string with parts of another
使用C#,最有效的方法是什么?
string one = "(999) 999-9999";
string two = "2221239876";
// combine these into result
result = "(222) 123-9876"
字符串一將始終有9。
我正在考慮在字符串1上使用某種foreach,當它看到9時,將其替換為字符串2中的下一個字符。 不太確定從那里去哪里...
如果要將某種格式應用於數字,可以嘗試以下方法:
long number = 2221239876;
string result = number.ToString("(###) ### ####"); // Result: (222) 123 9876
有關更多信息,請參閱.NET Framework文檔中的自定義數字格式字符串 。
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);
}
}
我不太清楚你期望模式(字符串'one')有多大差異。 如果它總是看起來像你已經顯示它,也許你可以用'#'替換9並使用.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;
}
}
顯然,你應該檢查以確保如果任何一個字符串比另一個字符串“更長”,那么就不會發生IndexOutOfRange異常(也就是說,'one'包含的內容多於'two'的長度等等)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.