2017-05-31 42 views
-5

我需要將字符串「DT1OutPassFail」更改爲「DT4OutPassFail」。我需要在輸入字符串中找到「DT1」並將其替換爲「DT4」以獲取輸出字符串。我需要使用c#來做到這一點。 「DT1」是textbox1中的值,「DT4」是textbox2中的值。我嘗試了以下選項。但它的工作。使用c替換一個詞的一部分#

string input = "DT1OutPassFail"; 
string newstring; 

newstring = input.Replace(textbox1.Text, textbox2.Text); 

newstring = Regex.Replace(input,textbox1.Text, textbox2.Text); 

回答

0
public string replaceString(string value) 
{ 
    string newValue; 
    string findValue; 
    string replaceValue; 

    findValue = textBox1.Text; 
    replaceValue = textBox2.Text; 

    if(value.StartsWith(findValue)) 
     newValue = value.Replace(findValue, replaceValue); 
    else 
     newValue = value; 

    return newValue; 
} 
0

嘗試,而不是這樣:

//The Original string 
string input = "DT1OutPassFail"; 
//The string which you want to replace with DT1 
string input2="DT4"; 
//Just check whether the string contains DT1 then replace it with input2 
var result = input.Contains("DT1") ? input.Replace("DT1", input2) : input; 
相關問題