我想创建一个应用程序,用于过滤字符串中数据库中的所有坏词。问题是替换不起作用。
private void checkmessage(string message)
{
try
{
if (string.IsNullOrEmpty(message))
{
MessageBox.Show("foutmelding 102, neem contact op met de beheerder");
} else
{
ArrayList names = new ArrayList();
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=twitterwall;Integrated Security=True");
SqlCommand command = new SqlCommand
(
"SELECT * FROM blacklist", conn
);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
names.Add(reader["name"].ToString());
}
conn.Close();
} catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
foreach (string x in names)
{
if (message.Contains(x))
{
message.Replace(x, " ***** ");
}
}
txtbericht.Text = "completed " + message;
}
} catch {
MessageBox.Show("Foutmelding 101");
}
}
答案 0 :(得分:3)
“不工作”不是一个问题,但我会试着指出你正确的方向进入“工作”版本。
我建议您阅读有关Replace
方法的文档。
你会在文档中找到这个片段:
返回一个新字符串,其中当前实例中所有出现的指定字符串都被另一个指定的字符串替换。
但在你的代码中有“
if (message.Contains(x))
{
message.Replace(x, " ***** ");
}
要解决此问题,您必须使用Replace
方法的返回值:
if (message.Contains(x))
{
message = message.Replace(x, " ***** ");
}
答案 1 :(得分:0)
字符串Replace()
不进行原位替换,它返回一个新的字符串,其值已按要求替换。