将字符串转换为三个字母缩写

时间:2016-01-04 12:37:59

标签: c# arrays string split logic

我最近获得了一个新项目,将任何给定的字符串转换为1-3个字母的缩写。 下面给出的字符串可以是任何东西:

switch (string.Name)
        {
            case "Emotional, Social & Personal": return "ESP";
            case "Speech & Language": return "SL";
            case "Physical Development": return "PD";
            case "Understanding the World": return "UW";
            case "English": return "E";
            case "Expressive Art & Design": return "EAD";
            case "Science": return "S";
            case "Understanding The World And It's People"; return "UTW";

}

我想我可以使用string.Split&计算数组中的单词数。然后添加处理特定长度字符串的条件,因为这些句子通常不会长于4个字,但我会遇到的问题是。

  1. 如果字符串比我预期的长,则不会处理
  2. 必须从缩写
  3. 中排除符号

    对于我可以应用的逻辑的任何建议都将非常感激。 感谢

4 个答案:

答案 0 :(得分:5)

以下内容应与您提供的示例一起使用。

string abbreviation = new string(
    input.Split()
          .Where(s => s.Length > 0 && char.IsLetter(s[0]) && char.IsUpper(s[0]))
          .Take(3)
          .Select(s => s[0])
          .ToArray());

您可能需要根据预期输入调整过滤器。可能会添加要忽略的单词列表。

答案 1 :(得分:1)

似乎如果不重要,你可以选择最简单的事情。如果字符串短于4个字,请取每个字符串的第一个字母。 如果字符串长于4,则删除所有" ands"和" ors",然后执行相同操作。

为了更好,你可以拥有一个你不会关心的单词查找词典 - 比如"""或"所以"。

您还可以按字母顺序保留3D字符数组,以便快速查找。这样,你就不会有任何重复的缩写。

但是,只有有限数量的缩写。因此,保持“无用”可能会更好。存储在另一个字符串中这样,如果您的程序默认执行的缩写已经被使用,您可以使用无用的单词来创建一个新的。

如果上述所有方法都失败了,你可以开始线性移动字符串以获得不同的3个字母的单词缩写 - 有点像DNA上的密码子。

答案 2 :(得分:0)

使用字典的理想场所

           Dictionary<string, string> dict = new Dictionary<string, string>() {
                {"Emotional, Social & Personal", "ESP"},
                {"Speech & Language","SL"},
                {"Physical Development", "PD"}, 
                {"Understanding the World","UW"},
                {"English","E"},
                {"Expressive Art & Design","EAD"},
                {"Science","S"},
                {"Understanding The World And It's People","UTW"}
            };

            string results = dict["English"];​

答案 3 :(得分:0)

以下代码段可以帮助您:

string input = "Emotional, Social & Personal"; // an example from the question 
string plainText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Regex.Replace(input, @"[^0-9A-Za-z ,]", "").ToLower()); // will produce a text without special charactors
string abbreviation = String.Join("",plainText.Split(" ".ToCharArray(),StringSplitOptions.RemoveEmptyEntries).Select(y =>y[0]).ToArray());// get first character from each word
相关问题