字符串,单词到单词翻译

时间:2013-08-16 11:39:14

标签: c# string list dictionary translation

我有一个班级

class dictonary
{
  public string English{get;set;}
  public string Hindi{get;set;}
}

这里我有一个类字典列表,List<dictionary>有英文和印地文的含义。 我希望功能为

public string EngToHindi(string English)
{
   private string hindi="";
   //nepali = english =>Logic goes here
   return hindi;
}

如果我传递"My Name Is Manoj."之类的字符串 然后它必须返回"Mera Naam hai Manoj"

List<dictionary>我的数据数据为

   English   Hindi
---------------------
    my        mera
    is        hai
    Name     naam

2 个答案:

答案 0 :(得分:2)

使用Dictionary类。它完美无缺。这是您可以使用的完整程序。它很容易,它将定义整条线!快乐的编码! ;)

class Program
{
    private static Dictionary<string, string> myDictionary;
    static void Main(string[] args)
    {
        // initialize your dictionary
        myDictionary = new Dictionary<string, string>(); 

        // fill the dictionary
        // you should fill if from file or database or something!
        myDictionary.Add("my", "mera");
        myDictionary.Add("is", "hai");
        myDictionary.Add("name", "naam");

        // the line you want to define in english:
        string line = "my name is Shamim";

        // output defined line in hindi:
        string output = EngLineToHindi(line);
        Console.WriteLine(output);
        Console.ReadKey();
    }
    static string EngLineToHindi(string line)
    {
        // array of words:
        string[] words = line.Split(' ');
        string ToReturn = "";
        foreach (string word in words)
        {
            string temp = EngToHindi(word) + " ";
            ToReturn += temp;
        }
        return ToReturn;
    }
    static string EngToHindi(string EngWord)
    {
        string key1 = EngWord;
        // if not has the meaning return the same word!
        if (!myDictionary.ContainsKey(key1)) return EngWord;
        else return myDictionary[key1];
    }
}

答案 1 :(得分:-1)

这可能有用......

Dictionary<string, string> EnglishHindiTranslations = null;

public void Populate()
{
    EnglishHindiTranslations = new Dictionary<string, string>();
    EnglishHindiTranslations.Add("my","mera");
    EnglishHindiTranslations.Add("is","hai");
    EnglishHindiTranslations.Add("Name","naam");
}

public string TranslateHindiToEnglish(string hindiWord)
{
    string value = EnglishHindiTranslations.FirstOrDefault(x => x.Value == hindiWord).Key;

    if(string.IsNullOrEmpty(value))
    {
         return hindiWord;
    }

    return value;
 }

public string TranslateEnglishToHindi(string englishWord)
{
    string value = EnglishHindiTranslations.FirstOrDefault(x => x.Key == englishWord).Value;

    if(string.IsNullOrEmpty(value))
    {
         return englishWord;
    }

    return value;
}