使用c替换一个词的一部分#

问题描述:

我需要将字符串“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); 

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; 
} 

尝试,而不是这样:

//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;