C# 使用C将所有引号设置为双引号#
我试图让用户能够在CustomerName中搜索带有报价的客户 用户搜索设置为customerNameTB的CustomerNametBox中的用户 如果用户使用引号('),它将替换为双引号 如果有一个三引号(“”),它将被替换为一个双引号 这是我的代码:C# 使用C将所有引号设置为双引号#,c#,double-quotes,quote,C#,Double Quotes,Quote,我试图让用户能够在CustomerName中搜索带有报价的客户 用户搜索设置为customerNameTB的CustomerNametBox中的用户 如果用户使用引号('),它将替换为双引号 如果有一个三引号(“”),它将被替换为一个双引号 这是我的代码: string customerNameTB = customerNameTextbox.Text; customerNameTB.Replace("'", "''"); whil
string customerNameTB = customerNameTextbox.Text;
customerNameTB.Replace("'", "''");
while (customerNameTB.Contains("'''"))
{
customerNameTB.Replace("'''", "''");
}
这段代码之后的结果是引号仍然是单引号
这段代码有什么问题
在回答后编辑
我的代码应该如下所示:
string customerNameTB = customerNameTextbox.Text;
customerNameTB = customerNameTB.Replace("'", "''");
while (customerNameTB.Contains("'''"))
{
customerNameTB = customerNameTB.Replace("'''", "''");
}
你接近了!这就是您需要的:
string customerNameTB = customerNameTextbox.Text;
// single quotes
customerNameTB = customerNameTB.Replace("'", "''");
// triple quotes
customerNameTB = customerNameTB.Replace("'''", "''");
replace不会在原始字符串中替换它,它会返回一个新字符串,您必须将该字符串分配给某个对象,否则它就会被丢弃。您很接近了!这就是您需要的:
string customerNameTB = customerNameTextbox.Text;
// single quotes
customerNameTB = customerNameTB.Replace("'", "''");
// triple quotes
customerNameTB = customerNameTB.Replace("'''", "''");
replace不会在原始字符串中替换它,它会返回一个必须分配给某个对象的新字符串,否则它会被丢弃。string.replace不会修改它正在运行的字符串。 您需要将替换结果分配给字符串:
string customerNameTB = customerNameTextbox.Text;
customerNameTB=customerNameTB.Replace("'", "''");
customerNameTB=customerNameTB.Replace("'''", "''");
此外,不需要循环,因为Replace会替换搜索字符串的所有匹配项。string.Replace不会修改它正在运行的字符串。 您需要将替换结果分配给字符串:
string customerNameTB = customerNameTextbox.Text;
customerNameTB=customerNameTB.Replace("'", "''");
customerNameTB=customerNameTB.Replace("'''", "''");
此外,不需要循环,因为Replace会替换搜索字符串的所有匹配项。我真的希望这不会连接到SQL查询中?如果是的话,你可能应该去读一读,以及如何防止它。我真的希望这不会连接到SQL查询中?如果是的话,你可能应该去读一读,以及如何防止它。循环是针对一行中有6个单引号的东西。这将首先用2替换第一个3,然后用2替换第二个3,剩下4。下一个循环将用2替换前3个,剩下3个,然后在最后一个循环中用2替换3个。现在,OP想要的东西是否正确是另一个问题。循环是指一行中有6个单引号的东西。这将首先用2替换第一个3,然后用2替换第二个3,剩下4。下一个循环将用2替换前3个,剩下3个,然后在最后一个循环中用2替换3个。现在,OP想要的是正确的天气是另一个问题。你也可以将Replace()链接起来。例如Replace().Replace()etc@Darren你是说像这样?customerNameTB=customerNameTB.Replace(“,”).Replace(“”);即使是这样,我个人还是更喜欢原作的可读性。-是的,这就是我的意思。当然,拆分一个更具可读性。这只是一条注释,您也可以链接这些字符串函数:)您也可以链接Replace()。例如Replace().Replace()etc@Darren你是说像这样?customerNameTB=customerNameTB.Replace(“,”).Replace(“”);即使是这样,我个人还是更喜欢原作的可读性。-是的,这就是我的意思。当然,拆分一个更具可读性。只是一条注释,您也可以链接这些字符串函数:)