2015-06-01 33 views
0

我輸入的是[email protected]適當的方法來替換一個字符串?

我想mnop.com

更換xyz.com所以最終的結果將是[email protected]

本辦法

var input = "[email protected]"; 
var output = input.Split('@')[0] + "@mnop.com"; 

什麼是適當的方式?任何規則表達?

+3

我覺得這是好的。 – anubhava

+0

如果你想用Y替換X,爲什麼不'input.Replace(X,Y);'?沒有必要使用正則表達式或分割 –

+0

是的,沒關係,常規對於此任務來說很昂貴。 –

回答

1

替換功能樣品(使用正確的例外處理)

/// <summary> 
/// replace email domain 
/// </summary> 
/// <param name="email"> email </param> 
/// <param name="newDomain"> new domain </param> 
/// <returns></returns> 
private string ReplaceMailDomain(string email, string newDomain) 
{ 
    if (email == null) throw new ArgumentNullException("email"); 

    int pos = email.IndexOf('@'); 
    if (pos < 0) 
    { 
     throw new ArgumentException("Invalid email", "email"); 
    } 
    else 
    { 
     return email.Substring(0, pos + 1) + newDomain; 
    } 
} 

用法:

string email = ReplaceMailDomain("[email protected]", "mnop.com"); 
-2

假設地址將是有效的,這意味着只有一個@符號,你可以使用簡單Replace()功能

var domain = "xyz.com"; 
var newdomain = "xyz.com"; 

var input = "[email protected]"; 
var output = input.Replace("@" + domain, "@" + newdomain); 

正則表達式將是矯枉過正這一點。

如果你想刪除任何域名和替換它,然後用Substring()IndexOf()

var output = input.Substring(0, input.IndexOf('@') + 1) + newdomain; 

注意,這將拋出一個異常,如果字符串不包含@字符。

+1

如果xyz.com在編譯時不知道?此外,「*分裂是爲這個*矯枉過正」,嚴重? – James

+1

@James那麼這是另一個問題,對吧? –

+1

我真的不明白基於「OP *可能*想要不同的東西」而沒有明確表示這種說法。 –

0

如果您事先知道您正在尋找的字符串,您可以簡單地使用正常的Replace(string toFind, string replacement)。您可以使用indexofsubstring來獲取域名。

鑑於以下:

 string input = "[email protected]"; 
     string domain = input.Substring(input.IndexOf('@') + 1); 
     Console.WriteLine(input.Replace(domain, "mnop.com")); 

它產生

[email protected] 
0

如果你只是想「拿東西之前@標誌和追加一些域名」,那麼可能的方法之一是

var input = "[email protected]"; 
var output = input.Substring(0, input.IndexOf('@')) + "@mnop.com"; 

它比使用稍微「輕」 10,因爲它不會創建數組(事實上,由於您只使用其第一個元素,所以不需要數組)。

相關問題