2010-02-19 134 views
3

使用C#,完成此操作的最有效方法是什麼?C#如何用另一個部分替換一個字符串的部分

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

// combine these into result 

result = "(222) 123-9876" 

字符串之一將始終有9個。

我在想一些字符串one的foreach,當它看到一個9時,用字符串2中的下一個字符替換它。不太清楚從哪裏出現,雖然去...

+0

問號是否意味着在第一個位置可能有或沒有數字。例如,如果掩碼爲9?9999的示例0123會導致0123? – 2010-02-19 22:48:20

+0

你只是想將10個數字的字符串格式化爲電話號碼嗎?因爲,有一種更簡單的方法來做到這一點在c# – 2010-02-19 22:50:00

+0

@Yuriy - 通過打出問號來簡化問題。 @Chris - 是的,我可以使用String.Format作爲電話號碼。但我在這裏想知道任何類型的面具。學術排序:) – macca1 2010-02-19 22:52:53

回答

12

如果要一定的格式應用到一個號碼,你可以試試這個:

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

欲瞭解更多信息,請參閱Custom Numeric Format Strings在.NET框架文檔。

0

我不太清楚你期望模式(字符串'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異常包含比'2'長度更多的九等)

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); 
    } 
} 
相關問題