在C#中添加数组的字符

时间:2015-03-14 09:42:38

标签: c# visual-studio-2013

我正在尝试制作一个简单的爱情计算器。我已预先定义了所有字符值,如a = 1,b = 2和all。但问题是我不知道如何计算长度并逐个添加所有字符。

1 个答案:

答案 0 :(得分:1)

如果a = 1,b = 2,...,z = 26

,你可以做什么的简单例子
string name = "Amélie Benoît Françoise Ågot Annbjørg";

// We transform letters with diacritics to "pure" letters (é->e, ç ->c...)
string normalized = name.Normalize(NormalizationForm.FormD);
var onlyLetters = normalized.Where(x => x >= 'A' && x <= 'Z' || x >= 'a' && x <= 'z');

// Note that the ø of Annbjørg will be stripped :-(
string strippedName = new string(onlyLetters.ToArray());
Console.WriteLine("Calculating for {0}", strippedName);

int sum = 0;

foreach (char ch in onlyLetters)
{
    char ch2 = char.ToUpper(ch);

    // char have a value... 'A' == 65, 'B' == 66 and so on,
    sum += ch2 - 'A' + 1;
}

// Done

请注意,此代码在Turky中将以不完整的方式工作,因为它们有4 i :-)挪威的名字甚至存在ø的问题,而没有说出不使用“ø”的名称欧洲“字母: - )

完整示例:http://ideone.com/ZHHU4G

您可以使用此方法(应与Windows应用商店兼容)替换Normalize方法调用:

public enum NORM_FORM
{
    NormalizationOther = 0,
    NormalizationC = 0x1,
    NormalizationD = 0x2,
    NormalizationKC = 0x5,
    NormalizationKD = 0x6
};

[DllImport("Normaliz.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
public static extern int NormalizeString(NORM_FORM NormForm,
    string lpSrcString,
    int cwSrcLength,
    StringBuilder lpDstString,
    int cwDstLength);

public static string NormalizeString(string unnormalized, NORM_FORM form)
{
    if (unnormalized == string.Empty)
    {
        return unnormalized;
    }

    int bufferSize = NormalizeString(form, unnormalized, unnormalized.Length, null, 0);

    if (bufferSize <= 0)
    {
        throw new Exception(string.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));
    }

    var sb = new StringBuilder(bufferSize);

    int result = NormalizeString(form, unnormalized, unnormalized.Length, sb, bufferSize);

    if (result <= 0)
    {
        throw new Exception(string.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));
    }

    return sb.ToString();
}

string normalized = NormalizeString(name, NORM_FORM.NormalizationD);