在c#字符串中查找字典中的单词和该单词的值

本文关键字:单词 字典 字符串 查找 | 更新日期: 2023-09-27 18:12:25

现在我有这段代码检查一个字符串是否在字典中有任意单词:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PlayerIOClient;
public static Connection conn;
public static Client client;
public static Dictionary<int, string> users = new Dictionary<int, string>();
public static Dictionary<string, string> corList = new Dictionary<string, string>();
public bool isConnected;
static void OnMessage(object sender, PlayerIOClient.Message m)
{
    if (m.Type == "init")
    {
        conn.Send("access", wldcode);
        conn.Send("init2");
        corList.Add("hes", "he's"); //Example of one item on the list.
        conn.Send("say", "Grammar fixer bot connected. Repare to be corrected.");
    }
    if (m.Type == "add")
    {
        users.Add(m.GetInt(0), m.GetString(1));
    }
    if (m.Type == "left")
    {
        users.Remove(m.GetInt(0));
    }
    if (m.Type == "say")
    {
        if (users.ContainsKey(m.GetInt(0)))
        {
            string username = users[m.GetInt(0)];
            if (corList.Keys.Any(m.GetString(1).Contains)) //Problem is here.
            { //m.GetString(1) Are usually long strings, such as sentences.
                conn.Send("say", "Grammar Fixer: " + corList[]);
            }
        }
    }
}

但是,我无法获得在单词中检测到的特定键或此键的值。这个字典也将包含很多定义,所以只对一个特定的单词使用if then是行不通的。

在c#字符串中查找字典中的单词和该单词的值

var key = m.GetString(1);
string correction = null;
if (corList.TryGetValue(key, out correction))
{
    conn.Send("say", string.format("Grammar Fixer: {0}, not {1}!", correction, key));
}

没有看到corList是什么或者m.GetString(1).Contains是什么很难说。所以我不得不猜测你想要做什么,但是你可以试试这个:

var key = m.GetString(1);
if (corList.Keys.Any(key))
{
    conn.Send("say", string.format("Grammar Fixer: {0}, not {1}!", corList[key], key));
}